1 // ignore-tidy-filelength
3 //! Numeric traits and functions for the built-in numeric types.
5 #![stable(feature = "rust1", since = "1.0.0")]
7 use crate::convert::Infallible;
11 use crate::ops::{BitOr, BitOrAssign};
12 use crate::str::FromStr;
14 // Used because the `?` operator is not allowed in a const context.
15 macro_rules! try_opt {
24 macro_rules! impl_nonzero_fmt {
25 ( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
28 impl fmt::$Trait for $Ty {
30 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38 macro_rules! doc_comment {
39 ($x:expr, $($tt:tt)*) => {
45 macro_rules! nonzero_integers {
46 ( $( #[$stability: meta] $Ty: ident($Int: ty); )+ ) => {
49 concat!("An integer that is known not to equal zero.
51 This enables some memory layout optimization.
52 For example, `Option<", stringify!($Ty), ">` is the same size as `", stringify!($Int), "`:
55 use std::mem::size_of;
56 assert_eq!(size_of::<Option<core::num::", stringify!($Ty), ">>(), size_of::<", stringify!($Int),
60 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
62 #[rustc_layout_scalar_valid_range_start(1)]
63 #[rustc_nonnull_optimization_guaranteed]
68 /// Creates a non-zero without checking the value.
72 /// The value must not be zero.
74 #[rustc_const_stable(feature = "nonzero", since = "1.34.0")]
76 pub const unsafe fn new_unchecked(n: $Int) -> Self {
80 /// Creates a non-zero if the given value is not zero.
82 #[rustc_const_unstable(feature = "const_nonzero_int_methods", issue = "53718")]
84 pub const fn new(n: $Int) -> Option<Self> {
86 // SAFETY: we just checked that there's no `0`
87 Some(unsafe { Self(n) })
93 /// Returns the value as a primitive type.
96 #[rustc_const_stable(feature = "nonzero", since = "1.34.0")]
97 pub const fn get(self) -> $Int {
103 #[stable(feature = "from_nonzero", since = "1.31.0")]
104 impl From<$Ty> for $Int {
107 "Converts a `", stringify!($Ty), "` into an `", stringify!($Int), "`"),
108 fn from(nonzero: $Ty) -> Self {
114 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
118 fn bitor(self, rhs: Self) -> Self::Output {
119 // Safety: since `self` and `rhs` are both nonzero, the
120 // result of the bitwise-or will be nonzero.
121 unsafe { $Ty::new_unchecked(self.get() | rhs.get()) }
125 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
126 impl BitOr<$Int> for $Ty {
129 fn bitor(self, rhs: $Int) -> Self::Output {
130 // Safety: since `self` is nonzero, the result of the
131 // bitwise-or will be nonzero regardless of the value of
133 unsafe { $Ty::new_unchecked(self.get() | rhs) }
137 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
138 impl BitOr<$Ty> for $Int {
141 fn bitor(self, rhs: $Ty) -> Self::Output {
142 // Safety: since `rhs` is nonzero, the result of the
143 // bitwise-or will be nonzero regardless of the value of
145 unsafe { $Ty::new_unchecked(self | rhs.get()) }
149 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
150 impl BitOrAssign for $Ty {
152 fn bitor_assign(&mut self, rhs: Self) {
157 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
158 impl BitOrAssign<$Int> for $Ty {
160 fn bitor_assign(&mut self, rhs: $Int) {
166 #[$stability] (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
173 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU8(u8);
174 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU16(u16);
175 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU32(u32);
176 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU64(u64);
177 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU128(u128);
178 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroUsize(usize);
179 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI8(i8);
180 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI16(i16);
181 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI32(i32);
182 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI64(i64);
183 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI128(i128);
184 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroIsize(isize);
187 macro_rules! from_str_radix_nzint_impl {
189 #[stable(feature = "nonzero_parse", since = "1.35.0")]
190 impl FromStr for $t {
191 type Err = ParseIntError;
192 fn from_str(src: &str) -> Result<Self, Self::Err> {
193 Self::new(from_str_radix(src, 10)?)
194 .ok_or(ParseIntError {
195 kind: IntErrorKind::Zero
202 from_str_radix_nzint_impl! { NonZeroU8 NonZeroU16 NonZeroU32 NonZeroU64 NonZeroU128 NonZeroUsize
203 NonZeroI8 NonZeroI16 NonZeroI32 NonZeroI64 NonZeroI128 NonZeroIsize }
205 /// Provides intentionally-wrapped arithmetic on `T`.
207 /// Operations like `+` on `u32` values are intended to never overflow,
208 /// and in some debug configurations overflow is detected and results
209 /// in a panic. While most arithmetic falls into this category, some
210 /// code explicitly expects and relies upon modular arithmetic (e.g.,
213 /// Wrapping arithmetic can be achieved either through methods like
214 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
215 /// all standard arithmetic operations on the underlying value are
216 /// intended to have wrapping semantics.
218 /// The underlying value can be retrieved through the `.0` index of the
219 /// `Wrapping` tuple.
224 /// use std::num::Wrapping;
226 /// let zero = Wrapping(0u32);
227 /// let one = Wrapping(1u32);
229 /// assert_eq!(u32::MAX, (zero - one).0);
231 #[stable(feature = "rust1", since = "1.0.0")]
232 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
234 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")] pub T);
236 #[stable(feature = "rust1", since = "1.0.0")]
237 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
238 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
243 #[stable(feature = "wrapping_display", since = "1.10.0")]
244 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
245 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
251 impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
252 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
257 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
258 impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
259 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
264 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
265 impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
266 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
271 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
272 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
273 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
278 // All these modules are technically private and only exposed for coretests:
286 macro_rules! usize_isize_to_xe_bytes_doc {
290 **Note**: This function returns an array of length 2, 4 or 8 bytes
291 depending on the target pointer size.
297 macro_rules! usize_isize_from_xe_bytes_doc {
301 **Note**: This function takes an array of length 2, 4 or 8 bytes
302 depending on the target pointer size.
308 macro_rules! int_impl {
309 ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $Min:expr, $Max:expr, $Feature:expr,
310 $EndFeature:expr, $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
311 $reversed:expr, $le_bytes:expr, $be_bytes:expr,
312 $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
314 concat!("The smallest value that can be represented by this integer type.
321 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MIN, ", stringify!($Min), ");",
324 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
325 pub const MIN: Self = !0 ^ ((!0 as $UnsignedT) >> 1) as Self;
329 concat!("The largest value that can be represented by this integer type.
336 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($Max), ");",
339 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
340 pub const MAX: Self = !Self::MIN;
344 concat!("Converts a string slice in a given base to an integer.
346 The string is expected to be an optional `+` or `-` sign followed by digits.
347 Leading and trailing whitespace represent an error. Digits are a subset of these characters,
348 depending on `radix`:
356 This function panics if `radix` is not in the range from 2 to 36.
363 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
366 #[stable(feature = "rust1", since = "1.0.0")]
367 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
368 from_str_radix(src, radix)
373 concat!("Returns the number of ones in the binary representation of `self`.
380 ", $Feature, "let n = 0b100_0000", stringify!($SelfT), ";
382 assert_eq!(n.count_ones(), 1);",
386 #[stable(feature = "rust1", since = "1.0.0")]
387 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
389 pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
393 concat!("Returns the number of zeros in the binary representation of `self`.
400 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX.count_zeros(), 1);", $EndFeature, "
402 #[stable(feature = "rust1", since = "1.0.0")]
403 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
405 pub const fn count_zeros(self) -> u32 {
411 concat!("Returns the number of leading zeros in the binary representation of `self`.
418 ", $Feature, "let n = -1", stringify!($SelfT), ";
420 assert_eq!(n.leading_zeros(), 0);",
423 #[stable(feature = "rust1", since = "1.0.0")]
424 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
426 pub const fn leading_zeros(self) -> u32 {
427 (self as $UnsignedT).leading_zeros()
432 concat!("Returns the number of trailing zeros in the binary representation of `self`.
439 ", $Feature, "let n = -4", stringify!($SelfT), ";
441 assert_eq!(n.trailing_zeros(), 2);",
444 #[stable(feature = "rust1", since = "1.0.0")]
445 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
447 pub const fn trailing_zeros(self) -> u32 {
448 (self as $UnsignedT).trailing_zeros()
453 concat!("Returns the number of leading ones in the binary representation of `self`.
460 ", $Feature, "#![feature(leading_trailing_ones)]
461 let n = -1", stringify!($SelfT), ";
463 assert_eq!(n.leading_ones(), ", stringify!($BITS), ");",
466 #[unstable(feature = "leading_trailing_ones", issue = "57969")]
468 pub const fn leading_ones(self) -> u32 {
469 (self as $UnsignedT).leading_ones()
474 concat!("Returns the number of trailing ones in the binary representation of `self`.
481 ", $Feature, "#![feature(leading_trailing_ones)]
482 let n = 3", stringify!($SelfT), ";
484 assert_eq!(n.trailing_ones(), 2);",
487 #[unstable(feature = "leading_trailing_ones", issue = "57969")]
489 pub const fn trailing_ones(self) -> u32 {
490 (self as $UnsignedT).trailing_ones()
495 concat!("Shifts the bits to the left by a specified amount, `n`,
496 wrapping the truncated bits to the end of the resulting integer.
498 Please note this isn't the same operation as the `<<` shifting operator!
505 let n = ", $rot_op, stringify!($SelfT), ";
506 let m = ", $rot_result, ";
508 assert_eq!(n.rotate_left(", $rot, "), m);
510 #[stable(feature = "rust1", since = "1.0.0")]
511 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
512 #[must_use = "this returns the result of the operation, \
513 without modifying the original"]
515 pub const fn rotate_left(self, n: u32) -> Self {
516 (self as $UnsignedT).rotate_left(n) as Self
521 concat!("Shifts the bits to the right by a specified amount, `n`,
522 wrapping the truncated bits to the beginning of the resulting
525 Please note this isn't the same operation as the `>>` shifting operator!
532 let n = ", $rot_result, stringify!($SelfT), ";
533 let m = ", $rot_op, ";
535 assert_eq!(n.rotate_right(", $rot, "), m);
537 #[stable(feature = "rust1", since = "1.0.0")]
538 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
539 #[must_use = "this returns the result of the operation, \
540 without modifying the original"]
542 pub const fn rotate_right(self, n: u32) -> Self {
543 (self as $UnsignedT).rotate_right(n) as Self
548 concat!("Reverses the byte order of the integer.
555 let n = ", $swap_op, stringify!($SelfT), ";
557 let m = n.swap_bytes();
559 assert_eq!(m, ", $swapped, ");
561 #[stable(feature = "rust1", since = "1.0.0")]
562 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
564 pub const fn swap_bytes(self) -> Self {
565 (self as $UnsignedT).swap_bytes() as Self
570 concat!("Reverses the bit pattern of the integer.
577 let n = ", $swap_op, stringify!($SelfT), ";
578 let m = n.reverse_bits();
580 assert_eq!(m, ", $reversed, ");
582 #[stable(feature = "reverse_bits", since = "1.37.0")]
583 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
586 pub const fn reverse_bits(self) -> Self {
587 (self as $UnsignedT).reverse_bits() as Self
592 concat!("Converts an integer from big endian to the target's endianness.
594 On big endian this is a no-op. On little endian the bytes are swapped.
601 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
603 if cfg!(target_endian = \"big\") {
604 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
606 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
610 #[stable(feature = "rust1", since = "1.0.0")]
611 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
613 pub const fn from_be(x: Self) -> Self {
614 #[cfg(target_endian = "big")]
618 #[cfg(not(target_endian = "big"))]
626 concat!("Converts an integer from little endian to the target's endianness.
628 On little endian this is a no-op. On big endian the bytes are swapped.
635 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
637 if cfg!(target_endian = \"little\") {
638 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
640 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
644 #[stable(feature = "rust1", since = "1.0.0")]
645 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
647 pub const fn from_le(x: Self) -> Self {
648 #[cfg(target_endian = "little")]
652 #[cfg(not(target_endian = "little"))]
660 concat!("Converts `self` to big endian from the target's endianness.
662 On big endian this is a no-op. On little endian the bytes are swapped.
669 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
671 if cfg!(target_endian = \"big\") {
672 assert_eq!(n.to_be(), n)
674 assert_eq!(n.to_be(), n.swap_bytes())
678 #[stable(feature = "rust1", since = "1.0.0")]
679 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
681 pub const fn to_be(self) -> Self { // or not to be?
682 #[cfg(target_endian = "big")]
686 #[cfg(not(target_endian = "big"))]
694 concat!("Converts `self` to little endian from the target's endianness.
696 On little endian this is a no-op. On big endian the bytes are swapped.
703 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
705 if cfg!(target_endian = \"little\") {
706 assert_eq!(n.to_le(), n)
708 assert_eq!(n.to_le(), n.swap_bytes())
712 #[stable(feature = "rust1", since = "1.0.0")]
713 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
715 pub const fn to_le(self) -> Self {
716 #[cfg(target_endian = "little")]
720 #[cfg(not(target_endian = "little"))]
728 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
729 if overflow occurred.
736 ", $Feature, "assert_eq!((", stringify!($SelfT),
737 "::MAX - 2).checked_add(1), Some(", stringify!($SelfT), "::MAX - 1));
738 assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);",
741 #[stable(feature = "rust1", since = "1.0.0")]
742 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
743 #[must_use = "this returns the result of the operation, \
744 without modifying the original"]
746 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
747 let (a, b) = self.overflowing_add(rhs);
748 if b {None} else {Some(a)}
753 concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
761 ", $Feature, "assert_eq!((", stringify!($SelfT),
762 "::MIN + 2).checked_sub(1), Some(", stringify!($SelfT), "::MIN + 1));
763 assert_eq!((", stringify!($SelfT), "::MIN + 2).checked_sub(3), None);",
766 #[stable(feature = "rust1", since = "1.0.0")]
767 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
768 #[must_use = "this returns the result of the operation, \
769 without modifying the original"]
771 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
772 let (a, b) = self.overflowing_sub(rhs);
773 if b {None} else {Some(a)}
778 concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
786 ", $Feature, "assert_eq!(", stringify!($SelfT),
787 "::MAX.checked_mul(1), Some(", stringify!($SelfT), "::MAX));
788 assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);",
791 #[stable(feature = "rust1", since = "1.0.0")]
792 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
793 #[must_use = "this returns the result of the operation, \
794 without modifying the original"]
796 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
797 let (a, b) = self.overflowing_mul(rhs);
798 if b {None} else {Some(a)}
803 concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
804 or the division results in overflow.
811 ", $Feature, "assert_eq!((", stringify!($SelfT),
812 "::MIN + 1).checked_div(-1), Some(", stringify!($Max), "));
813 assert_eq!(", stringify!($SelfT), "::MIN.checked_div(-1), None);
814 assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
817 #[stable(feature = "rust1", since = "1.0.0")]
818 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
819 #[must_use = "this returns the result of the operation, \
820 without modifying the original"]
822 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
823 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
826 // SAFETY: div by zero and by INT_MIN have been checked above
827 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
833 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`,
834 returning `None` if `rhs == 0` or the division results in overflow.
841 assert_eq!((", stringify!($SelfT),
842 "::MIN + 1).checked_div_euclid(-1), Some(", stringify!($Max), "));
843 assert_eq!(", stringify!($SelfT), "::MIN.checked_div_euclid(-1), None);
844 assert_eq!((1", stringify!($SelfT), ").checked_div_euclid(0), None);
846 #[stable(feature = "euclidean_division", since = "1.38.0")]
847 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
848 #[must_use = "this returns the result of the operation, \
849 without modifying the original"]
851 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
852 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
855 Some(self.div_euclid(rhs))
861 concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
862 `rhs == 0` or the division results in overflow.
870 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
871 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
872 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
875 #[stable(feature = "wrapping", since = "1.7.0")]
876 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
877 #[must_use = "this returns the result of the operation, \
878 without modifying the original"]
880 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
881 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
884 // SAFETY: div by zero and by INT_MIN have been checked above
885 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
891 concat!("Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`
892 if `rhs == 0` or the division results in overflow.
899 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
900 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
901 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem_euclid(-1), None);
903 #[stable(feature = "euclidean_division", since = "1.38.0")]
904 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
905 #[must_use = "this returns the result of the operation, \
906 without modifying the original"]
908 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
909 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
912 Some(self.rem_euclid(rhs))
918 concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
926 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
927 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
930 #[stable(feature = "wrapping", since = "1.7.0")]
931 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
933 pub const fn checked_neg(self) -> Option<Self> {
934 let (a, b) = self.overflowing_neg();
935 if b {None} else {Some(a)}
940 concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
941 than or equal to the number of bits in `self`.
948 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
949 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
952 #[stable(feature = "wrapping", since = "1.7.0")]
953 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
954 #[must_use = "this returns the result of the operation, \
955 without modifying the original"]
957 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
958 let (a, b) = self.overflowing_shl(rhs);
959 if b {None} else {Some(a)}
964 concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
965 larger than or equal to the number of bits in `self`.
972 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
973 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
976 #[stable(feature = "wrapping", since = "1.7.0")]
977 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
978 #[must_use = "this returns the result of the operation, \
979 without modifying the original"]
981 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
982 let (a, b) = self.overflowing_shr(rhs);
983 if b {None} else {Some(a)}
988 concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
997 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
998 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
1001 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1002 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
1004 pub const fn checked_abs(self) -> Option<Self> {
1005 if self.is_negative() {
1014 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
1022 ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
1023 assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);",
1027 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1028 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
1029 #[must_use = "this returns the result of the operation, \
1030 without modifying the original"]
1032 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
1033 let mut base = self;
1034 let mut acc: Self = 1;
1038 acc = try_opt!(acc.checked_mul(base));
1041 base = try_opt!(base.checked_mul(base));
1044 // Deal with the final bit of the exponent separately, since
1045 // squaring the base afterwards is not necessary and may cause a
1046 // needless overflow.
1048 acc = try_opt!(acc.checked_mul(base));
1056 concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
1057 bounds instead of overflowing.
1064 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
1065 assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(100), ", stringify!($SelfT),
1067 assert_eq!(", stringify!($SelfT), "::MIN.saturating_add(-1), ", stringify!($SelfT),
1072 #[stable(feature = "rust1", since = "1.0.0")]
1073 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1074 #[must_use = "this returns the result of the operation, \
1075 without modifying the original"]
1077 pub const fn saturating_add(self, rhs: Self) -> Self {
1078 intrinsics::saturating_add(self, rhs)
1083 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
1084 numeric bounds instead of overflowing.
1091 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
1092 assert_eq!(", stringify!($SelfT), "::MIN.saturating_sub(100), ", stringify!($SelfT),
1094 assert_eq!(", stringify!($SelfT), "::MAX.saturating_sub(-1), ", stringify!($SelfT),
1098 #[stable(feature = "rust1", since = "1.0.0")]
1099 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1100 #[must_use = "this returns the result of the operation, \
1101 without modifying the original"]
1103 pub const fn saturating_sub(self, rhs: Self) -> Self {
1104 intrinsics::saturating_sub(self, rhs)
1109 concat!("Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
1110 instead of overflowing.
1117 ", $Feature, "#![feature(saturating_neg)]
1118 assert_eq!(100", stringify!($SelfT), ".saturating_neg(), -100);
1119 assert_eq!((-100", stringify!($SelfT), ").saturating_neg(), 100);
1120 assert_eq!(", stringify!($SelfT), "::MIN.saturating_neg(), ", stringify!($SelfT),
1122 assert_eq!(", stringify!($SelfT), "::MAX.saturating_neg(), ", stringify!($SelfT),
1127 #[unstable(feature = "saturating_neg", issue = "59983")]
1128 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1130 pub const fn saturating_neg(self) -> Self {
1131 intrinsics::saturating_sub(0, self)
1136 concat!("Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
1137 MIN` instead of overflowing.
1144 ", $Feature, "#![feature(saturating_neg)]
1145 assert_eq!(100", stringify!($SelfT), ".saturating_abs(), 100);
1146 assert_eq!((-100", stringify!($SelfT), ").saturating_abs(), 100);
1147 assert_eq!(", stringify!($SelfT), "::MIN.saturating_abs(), ", stringify!($SelfT),
1149 assert_eq!((", stringify!($SelfT), "::MIN + 1).saturating_abs(), ", stringify!($SelfT),
1154 #[unstable(feature = "saturating_neg", issue = "59983")]
1155 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1157 pub const fn saturating_abs(self) -> Self {
1158 if self.is_negative() {
1159 self.saturating_neg()
1167 concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
1168 numeric bounds instead of overflowing.
1176 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
1177 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
1178 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
1181 #[stable(feature = "wrapping", since = "1.7.0")]
1182 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
1183 #[must_use = "this returns the result of the operation, \
1184 without modifying the original"]
1186 pub const fn saturating_mul(self, rhs: Self) -> Self {
1187 match self.checked_mul(rhs) {
1189 None => if (self < 0) == (rhs < 0) {
1199 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
1200 saturating at the numeric bounds instead of overflowing.
1208 assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
1209 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
1210 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
1213 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1214 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
1215 #[must_use = "this returns the result of the operation, \
1216 without modifying the original"]
1218 pub const fn saturating_pow(self, exp: u32) -> Self {
1219 match self.checked_pow(exp) {
1221 None if self < 0 && exp % 2 == 1 => Self::min_value(),
1222 None => Self::max_value(),
1228 concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
1229 boundary of the type.
1236 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
1237 assert_eq!(", stringify!($SelfT), "::MAX.wrapping_add(2), ", stringify!($SelfT),
1241 #[stable(feature = "rust1", since = "1.0.0")]
1242 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1243 #[must_use = "this returns the result of the operation, \
1244 without modifying the original"]
1246 pub const fn wrapping_add(self, rhs: Self) -> Self {
1247 intrinsics::wrapping_add(self, rhs)
1252 concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1253 boundary of the type.
1260 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
1261 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::MAX), ",
1262 stringify!($SelfT), "::MAX);",
1265 #[stable(feature = "rust1", since = "1.0.0")]
1266 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1267 #[must_use = "this returns the result of the operation, \
1268 without modifying the original"]
1270 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1271 intrinsics::wrapping_sub(self, rhs)
1276 concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1277 the boundary of the type.
1284 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
1285 assert_eq!(11i8.wrapping_mul(12), -124);",
1288 #[stable(feature = "rust1", since = "1.0.0")]
1289 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1290 #[must_use = "this returns the result of the operation, \
1291 without modifying the original"]
1293 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1294 intrinsics::wrapping_mul(self, rhs)
1299 concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1300 boundary of the type.
1302 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1303 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1304 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1308 This function will panic if `rhs` is 0.
1315 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
1316 assert_eq!((-128i8).wrapping_div(-1), -128);",
1319 #[stable(feature = "num_wrapping", since = "1.2.0")]
1320 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
1321 #[must_use = "this returns the result of the operation, \
1322 without modifying the original"]
1324 pub const fn wrapping_div(self, rhs: Self) -> Self {
1325 self.overflowing_div(rhs).0
1330 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
1331 wrapping around at the boundary of the type.
1333 Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1334 for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1335 type. In this case, this method returns `MIN` itself.
1339 This function will panic if `rhs` is 0.
1346 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
1347 assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
1349 #[stable(feature = "euclidean_division", since = "1.38.0")]
1350 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1351 #[must_use = "this returns the result of the operation, \
1352 without modifying the original"]
1354 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
1355 self.overflowing_div_euclid(rhs).0
1360 concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1361 boundary of the type.
1363 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1364 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1365 this function returns `0`.
1369 This function will panic if `rhs` is 0.
1376 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
1377 assert_eq!((-128i8).wrapping_rem(-1), 0);",
1380 #[stable(feature = "num_wrapping", since = "1.2.0")]
1381 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
1382 #[must_use = "this returns the result of the operation, \
1383 without modifying the original"]
1385 pub const fn wrapping_rem(self, rhs: Self) -> Self {
1386 self.overflowing_rem(rhs).0
1391 concat!("Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
1392 at the boundary of the type.
1394 Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1395 for the type). In this case, this method returns 0.
1399 This function will panic if `rhs` is 0.
1406 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
1407 assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
1409 #[stable(feature = "euclidean_division", since = "1.38.0")]
1410 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1411 #[must_use = "this returns the result of the operation, \
1412 without modifying the original"]
1414 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1415 self.overflowing_rem_euclid(rhs).0
1420 concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1423 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1424 is the negative minimal value for the type); this is a positive value that is too large to represent
1425 in the type. In such a case, this function returns `MIN` itself.
1432 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
1433 assert_eq!(", stringify!($SelfT), "::MIN.wrapping_neg(), ", stringify!($SelfT),
1437 #[stable(feature = "num_wrapping", since = "1.2.0")]
1438 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1440 pub const fn wrapping_neg(self) -> Self {
1441 self.overflowing_neg().0
1446 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1447 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1449 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1450 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1451 The primitive integer types all implement a `[`rotate_left`](#method.rotate_left) function,
1452 which may be what you want instead.
1459 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
1460 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
1463 #[stable(feature = "num_wrapping", since = "1.2.0")]
1464 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1465 #[must_use = "this returns the result of the operation, \
1466 without modifying the original"]
1468 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1469 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1472 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1478 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1479 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1481 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1482 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1483 end. The primitive integer types all implement a [`rotate_right`](#method.rotate_right) function,
1484 which may be what you want instead.
1491 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
1492 assert_eq!((-128i16).wrapping_shr(64), -128);",
1495 #[stable(feature = "num_wrapping", since = "1.2.0")]
1496 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1497 #[must_use = "this returns the result of the operation, \
1498 without modifying the original"]
1500 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1501 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1504 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1510 concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1511 the boundary of the type.
1513 The only case where such wrapping can occur is when one takes the absolute value of the negative
1514 minimal value for the type this is a positive value that is too large to represent in the type. In
1515 such a case, this function returns `MIN` itself.
1522 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
1523 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
1524 assert_eq!(", stringify!($SelfT), "::MIN.wrapping_abs(), ", stringify!($SelfT),
1526 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1529 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1530 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1531 #[allow(unused_attributes)]
1532 #[allow_internal_unstable(const_if_match)]
1534 pub const fn wrapping_abs(self) -> Self {
1535 if self.is_negative() {
1544 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1545 wrapping around at the boundary of the type.
1552 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);
1553 assert_eq!(3i8.wrapping_pow(5), -13);
1554 assert_eq!(3i8.wrapping_pow(6), -39);",
1557 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1558 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
1559 #[must_use = "this returns the result of the operation, \
1560 without modifying the original"]
1562 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
1563 let mut base = self;
1564 let mut acc: Self = 1;
1568 acc = acc.wrapping_mul(base);
1571 base = base.wrapping_mul(base);
1574 // Deal with the final bit of the exponent separately, since
1575 // squaring the base afterwards is not necessary and may cause a
1576 // needless overflow.
1578 acc = acc.wrapping_mul(base);
1586 concat!("Calculates `self` + `rhs`
1588 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1589 occur. If an overflow would have occurred then the wrapped value is returned.
1597 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1598 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
1599 "::MIN, true));", $EndFeature, "
1601 #[stable(feature = "wrapping", since = "1.7.0")]
1602 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1603 #[must_use = "this returns the result of the operation, \
1604 without modifying the original"]
1606 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1607 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1613 concat!("Calculates `self` - `rhs`
1615 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1616 would occur. If an overflow would have occurred then the wrapped value is returned.
1624 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
1625 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
1626 "::MAX, true));", $EndFeature, "
1628 #[stable(feature = "wrapping", since = "1.7.0")]
1629 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1630 #[must_use = "this returns the result of the operation, \
1631 without modifying the original"]
1633 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1634 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1640 concat!("Calculates the multiplication of `self` and `rhs`.
1642 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1643 would occur. If an overflow would have occurred then the wrapped value is returned.
1650 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1651 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1654 #[stable(feature = "wrapping", since = "1.7.0")]
1655 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1656 #[must_use = "this returns the result of the operation, \
1657 without modifying the original"]
1659 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1660 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1666 concat!("Calculates the divisor when `self` is divided by `rhs`.
1668 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1669 occur. If an overflow would occur then self is returned.
1673 This function will panic if `rhs` is 0.
1681 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1682 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1687 #[stable(feature = "wrapping", since = "1.7.0")]
1688 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
1689 #[must_use = "this returns the result of the operation, \
1690 without modifying the original"]
1691 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1692 if self == Self::min_value() && rhs == -1 {
1701 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1703 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1704 occur. If an overflow would occur then `self` is returned.
1708 This function will panic if `rhs` is 0.
1715 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
1716 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euclid(-1), (", stringify!($SelfT),
1720 #[stable(feature = "euclidean_division", since = "1.38.0")]
1721 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1722 #[must_use = "this returns the result of the operation, \
1723 without modifying the original"]
1724 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1725 if self == Self::min_value() && rhs == -1 {
1728 (self.div_euclid(rhs), false)
1734 concat!("Calculates the remainder when `self` is divided by `rhs`.
1736 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1737 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1741 This function will panic if `rhs` is 0.
1749 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1750 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1754 #[stable(feature = "wrapping", since = "1.7.0")]
1755 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
1756 #[must_use = "this returns the result of the operation, \
1757 without modifying the original"]
1758 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1759 if self == Self::min_value() && rhs == -1 {
1769 concat!("Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
1771 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1772 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1776 This function will panic if `rhs` is 0.
1783 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
1784 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem_euclid(-1), (0, true));
1786 #[stable(feature = "euclidean_division", since = "1.38.0")]
1787 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1788 #[must_use = "this returns the result of the operation, \
1789 without modifying the original"]
1791 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1792 if self == Self::min_value() && rhs == -1 {
1795 (self.rem_euclid(rhs), false)
1802 concat!("Negates self, overflowing if this is equal to the minimum value.
1804 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1805 happened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the
1806 minimum value will be returned again and `true` will be returned for an overflow happening.
1813 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1814 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1815 "::MIN, true));", $EndFeature, "
1818 #[stable(feature = "wrapping", since = "1.7.0")]
1819 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1820 #[allow(unused_attributes)]
1821 #[allow_internal_unstable(const_if_match)]
1822 pub const fn overflowing_neg(self) -> (Self, bool) {
1823 if self == Self::min_value() {
1824 (Self::min_value(), true)
1832 concat!("Shifts self left by `rhs` bits.
1834 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1835 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1836 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1843 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1844 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1847 #[stable(feature = "wrapping", since = "1.7.0")]
1848 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1849 #[must_use = "this returns the result of the operation, \
1850 without modifying the original"]
1852 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1853 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1858 concat!("Shifts self right by `rhs` bits.
1860 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1861 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1862 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1869 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1870 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1873 #[stable(feature = "wrapping", since = "1.7.0")]
1874 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1875 #[must_use = "this returns the result of the operation, \
1876 without modifying the original"]
1878 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1879 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1884 concat!("Computes the absolute value of `self`.
1886 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1887 happened. If self is the minimum value (e.g., ", stringify!($SelfT), "::MIN for values of type
1888 ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1889 for an overflow happening.
1896 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1897 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1898 assert_eq!((", stringify!($SelfT), "::MIN).overflowing_abs(), (", stringify!($SelfT),
1902 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1903 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1905 pub const fn overflowing_abs(self) -> (Self, bool) {
1906 (self.wrapping_abs(), self == Self::min_value())
1911 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1913 Returns a tuple of the exponentiation along with a bool indicating
1914 whether an overflow happened.
1921 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));
1922 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
1925 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1926 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
1927 #[must_use = "this returns the result of the operation, \
1928 without modifying the original"]
1930 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1931 let mut base = self;
1932 let mut acc: Self = 1;
1933 let mut overflown = false;
1934 // Scratch space for storing results of overflowing_mul.
1939 r = acc.overflowing_mul(base);
1944 r = base.overflowing_mul(base);
1949 // Deal with the final bit of the exponent separately, since
1950 // squaring the base afterwards is not necessary and may cause a
1951 // needless overflow.
1953 r = acc.overflowing_mul(base);
1963 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1970 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
1972 assert_eq!(x.pow(5), 32);",
1975 #[stable(feature = "rust1", since = "1.0.0")]
1976 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
1977 #[must_use = "this returns the result of the operation, \
1978 without modifying the original"]
1980 #[rustc_inherit_overflow_checks]
1981 pub const fn pow(self, mut exp: u32) -> Self {
1982 let mut base = self;
1993 // Deal with the final bit of the exponent separately, since
1994 // squaring the base afterwards is not necessary and may cause a
1995 // needless overflow.
2005 concat!("Calculates the quotient of Euclidean division of `self` by `rhs`.
2007 This computes the integer `n` such that `self = n * rhs + self.rem_euclid(rhs)`,
2008 with `0 <= self.rem_euclid(rhs) < rhs`.
2010 In other words, the result is `self / rhs` rounded to the integer `n`
2011 such that `self >= n * rhs`.
2012 If `self > 0`, this is equal to round towards zero (the default in Rust);
2013 if `self < 0`, this is equal to round towards +/- infinity.
2017 This function will panic if `rhs` is 0 or the division results in overflow.
2024 let a: ", stringify!($SelfT), " = 7; // or any other integer type
2027 assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
2028 assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
2029 assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
2030 assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
2032 #[stable(feature = "euclidean_division", since = "1.38.0")]
2033 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
2034 #[must_use = "this returns the result of the operation, \
2035 without modifying the original"]
2037 #[rustc_inherit_overflow_checks]
2038 pub const fn div_euclid(self, rhs: Self) -> Self {
2041 return if rhs > 0 { q - 1 } else { q + 1 }
2049 concat!("Calculates the least nonnegative remainder of `self (mod rhs)`.
2051 This is done as if by the Euclidean division algorithm -- given
2052 `r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) + r`, and
2053 `0 <= r < abs(rhs)`.
2057 This function will panic if `rhs` is 0 or the division results in overflow.
2064 let a: ", stringify!($SelfT), " = 7; // or any other integer type
2067 assert_eq!(a.rem_euclid(b), 3);
2068 assert_eq!((-a).rem_euclid(b), 1);
2069 assert_eq!(a.rem_euclid(-b), 3);
2070 assert_eq!((-a).rem_euclid(-b), 1);
2072 #[stable(feature = "euclidean_division", since = "1.38.0")]
2073 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
2074 #[must_use = "this returns the result of the operation, \
2075 without modifying the original"]
2077 #[rustc_inherit_overflow_checks]
2078 pub const fn rem_euclid(self, rhs: Self) -> Self {
2093 concat!("Computes the absolute value of `self`.
2097 The absolute value of `", stringify!($SelfT), "::MIN` cannot be represented as an
2098 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
2099 code in debug mode will trigger a panic on this case and optimized code will return `",
2100 stringify!($SelfT), "::MIN` without a panic.
2107 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
2108 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
2111 #[stable(feature = "rust1", since = "1.0.0")]
2112 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2113 #[allow(unused_attributes)]
2114 #[allow_internal_unstable(const_if_match)]
2116 #[rustc_inherit_overflow_checks]
2117 pub const fn abs(self) -> Self {
2118 // Note that the #[inline] above means that the overflow
2119 // semantics of the subtraction depend on the crate we're being
2121 if self.is_negative() {
2130 concat!("Returns a number representing sign of `self`.
2132 - `0` if the number is zero
2133 - `1` if the number is positive
2134 - `-1` if the number is negative
2141 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
2142 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
2143 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
2146 #[stable(feature = "rust1", since = "1.0.0")]
2147 #[rustc_const_unstable(feature = "const_int_sign", issue = "53718")]
2149 pub const fn signum(self) -> Self {
2159 concat!("Returns `true` if `self` is positive and `false` if the number is zero or
2167 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
2168 assert!(!(-10", stringify!($SelfT), ").is_positive());",
2171 #[stable(feature = "rust1", since = "1.0.0")]
2172 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2174 pub const fn is_positive(self) -> bool { self > 0 }
2178 concat!("Returns `true` if `self` is negative and `false` if the number is zero or
2186 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
2187 assert!(!10", stringify!($SelfT), ".is_negative());",
2190 #[stable(feature = "rust1", since = "1.0.0")]
2191 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2193 pub const fn is_negative(self) -> bool { self < 0 }
2197 concat!("Return the memory representation of this integer as a byte array in
2198 big-endian (network) byte order.
2205 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
2206 assert_eq!(bytes, ", $be_bytes, ");
2208 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2209 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2211 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2212 self.to_be().to_ne_bytes()
2217 concat!("Return the memory representation of this integer as a byte array in
2218 little-endian byte order.
2225 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
2226 assert_eq!(bytes, ", $le_bytes, ");
2228 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2229 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2231 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2232 self.to_le().to_ne_bytes()
2238 Return the memory representation of this integer as a byte array in
2241 As the target platform's native endianness is used, portable code
2242 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2247 [`to_be_bytes`]: #method.to_be_bytes
2248 [`to_le_bytes`]: #method.to_le_bytes
2253 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
2256 if cfg!(target_endian = \"big\") {
2263 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2264 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2265 // SAFETY: const sound because integers are plain old datatypes so we can always
2266 // transmute them to arrays of bytes
2267 #[allow_internal_unstable(const_fn_union)]
2269 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2273 bytes: [u8; mem::size_of::<$SelfT>()],
2275 // SAFETY: integers are plain old datatypes so we can always transmute them to
2277 unsafe { Bytes { val: self }.bytes }
2282 concat!("Create an integer value from its representation as a byte array in
2290 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
2291 assert_eq!(value, ", $swap_op, ");
2294 When starting from a slice rather than an array, fallible conversion APIs can be used:
2297 use std::convert::TryInto;
2299 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2300 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2302 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
2305 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2306 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2308 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2309 Self::from_be(Self::from_ne_bytes(bytes))
2315 Create an integer value from its representation as a byte array in
2323 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
2324 assert_eq!(value, ", $swap_op, ");
2327 When starting from a slice rather than an array, fallible conversion APIs can be used:
2330 use std::convert::TryInto;
2332 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2333 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2335 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
2338 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2339 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2341 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2342 Self::from_le(Self::from_ne_bytes(bytes))
2347 concat!("Create an integer value from its memory representation as a byte
2348 array in native endianness.
2350 As the target platform's native endianness is used, portable code
2351 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2352 appropriate instead.
2354 [`from_be_bytes`]: #method.from_be_bytes
2355 [`from_le_bytes`]: #method.from_le_bytes
2362 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
2367 assert_eq!(value, ", $swap_op, ");
2370 When starting from a slice rather than an array, fallible conversion APIs can be used:
2373 use std::convert::TryInto;
2375 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2376 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2378 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
2381 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2382 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2383 // SAFETY: const sound because integers are plain old datatypes so we can always
2384 // transmute to them
2385 #[allow_internal_unstable(const_fn_union)]
2387 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2391 bytes: [u8; mem::size_of::<$SelfT>()],
2393 // SAFETY: integers are plain old datatypes so we can always transmute to them
2394 unsafe { Bytes { bytes }.val }
2399 concat!("**This method is soft-deprecated.**
2401 Although using it won’t cause compilation warning,
2402 new code should use [`", stringify!($SelfT), "::MIN", "`](#associatedconstant.MIN) instead.
2404 Returns the smallest value that can be represented by this integer type."),
2405 #[stable(feature = "rust1", since = "1.0.0")]
2408 #[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
2409 pub const fn min_value() -> Self {
2415 concat!("**This method is soft-deprecated.**
2417 Although using it won’t cause compilation warning,
2418 new code should use [`", stringify!($SelfT), "::MAX", "`](#associatedconstant.MAX) instead.
2420 Returns the largest value that can be represented by this integer type."),
2421 #[stable(feature = "rust1", since = "1.0.0")]
2424 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2425 pub const fn max_value() -> Self {
2434 int_impl! { i8, i8, u8, 8, -128, 127, "", "", 2, "-0x7e", "0xa", "0x12", "0x12", "0x48",
2435 "[0x12]", "[0x12]", "", "" }
2440 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234", "0x3412",
2441 "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
2446 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2447 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2448 "[0x12, 0x34, 0x56, 0x78]", "", "" }
2453 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "", 12,
2454 "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2455 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2456 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]", "", "" }
2461 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
2462 170141183460469231731687303715884105727, "", "", 16,
2463 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
2464 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
2465 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
2466 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2467 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
2468 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]", "", "" }
2471 #[cfg(target_pointer_width = "16")]
2474 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234",
2475 "0x3412", "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]",
2476 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2479 #[cfg(target_pointer_width = "32")]
2482 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2483 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2484 "[0x12, 0x34, 0x56, 0x78]",
2485 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2488 #[cfg(target_pointer_width = "64")]
2491 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "",
2492 12, "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2493 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2494 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
2495 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
2498 macro_rules! uint_impl {
2499 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr,
2500 $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
2501 $reversed:expr, $le_bytes:expr, $be_bytes:expr,
2502 $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
2504 concat!("The smallest value that can be represented by this integer type.
2511 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MIN, 0);", $EndFeature, "
2513 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
2514 pub const MIN: Self = 0;
2518 concat!("The largest value that can be represented by this integer type.
2525 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($MaxV), ");",
2528 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
2529 pub const MAX: Self = !0;
2533 concat!("Converts a string slice in a given base to an integer.
2535 The string is expected to be an optional `+` sign
2537 Leading and trailing whitespace represent an error.
2538 Digits are a subset of these characters, depending on `radix`:
2546 This function panics if `radix` is not in the range from 2 to 36.
2553 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
2556 #[stable(feature = "rust1", since = "1.0.0")]
2557 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
2558 from_str_radix(src, radix)
2563 concat!("Returns the number of ones in the binary representation of `self`.
2570 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
2572 assert_eq!(n.count_ones(), 3);", $EndFeature, "
2574 #[stable(feature = "rust1", since = "1.0.0")]
2575 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2577 pub const fn count_ones(self) -> u32 {
2578 intrinsics::ctpop(self as $ActualT) as u32
2583 concat!("Returns the number of zeros in the binary representation of `self`.
2590 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX.count_zeros(), 0);", $EndFeature, "
2592 #[stable(feature = "rust1", since = "1.0.0")]
2593 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2595 pub const fn count_zeros(self) -> u32 {
2596 (!self).count_ones()
2601 concat!("Returns the number of leading zeros in the binary representation of `self`.
2608 ", $Feature, "let n = ", stringify!($SelfT), "::MAX >> 2;
2610 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
2612 #[stable(feature = "rust1", since = "1.0.0")]
2613 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2615 pub const fn leading_zeros(self) -> u32 {
2616 intrinsics::ctlz(self as $ActualT) as u32
2621 concat!("Returns the number of trailing zeros in the binary representation
2629 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
2631 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
2633 #[stable(feature = "rust1", since = "1.0.0")]
2634 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2636 pub const fn trailing_zeros(self) -> u32 {
2637 intrinsics::cttz(self) as u32
2642 concat!("Returns the number of leading ones in the binary representation of `self`.
2649 ", $Feature, "#![feature(leading_trailing_ones)]
2650 let n = !(", stringify!($SelfT), "::MAX >> 2);
2652 assert_eq!(n.leading_ones(), 2);", $EndFeature, "
2654 #[unstable(feature = "leading_trailing_ones", issue = "57969")]
2656 pub const fn leading_ones(self) -> u32 {
2657 (!self).leading_zeros()
2662 concat!("Returns the number of trailing ones in the binary representation
2670 ", $Feature, "#![feature(leading_trailing_ones)]
2671 let n = 0b1010111", stringify!($SelfT), ";
2673 assert_eq!(n.trailing_ones(), 3);", $EndFeature, "
2675 #[unstable(feature = "leading_trailing_ones", issue = "57969")]
2677 pub const fn trailing_ones(self) -> u32 {
2678 (!self).trailing_zeros()
2683 concat!("Shifts the bits to the left by a specified amount, `n`,
2684 wrapping the truncated bits to the end of the resulting integer.
2686 Please note this isn't the same operation as the `<<` shifting operator!
2693 let n = ", $rot_op, stringify!($SelfT), ";
2694 let m = ", $rot_result, ";
2696 assert_eq!(n.rotate_left(", $rot, "), m);
2698 #[stable(feature = "rust1", since = "1.0.0")]
2699 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2700 #[must_use = "this returns the result of the operation, \
2701 without modifying the original"]
2703 pub const fn rotate_left(self, n: u32) -> Self {
2704 intrinsics::rotate_left(self, n as $SelfT)
2709 concat!("Shifts the bits to the right by a specified amount, `n`,
2710 wrapping the truncated bits to the beginning of the resulting
2713 Please note this isn't the same operation as the `>>` shifting operator!
2720 let n = ", $rot_result, stringify!($SelfT), ";
2721 let m = ", $rot_op, ";
2723 assert_eq!(n.rotate_right(", $rot, "), m);
2725 #[stable(feature = "rust1", since = "1.0.0")]
2726 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2727 #[must_use = "this returns the result of the operation, \
2728 without modifying the original"]
2730 pub const fn rotate_right(self, n: u32) -> Self {
2731 intrinsics::rotate_right(self, n as $SelfT)
2737 Reverses the byte order of the integer.
2744 let n = ", $swap_op, stringify!($SelfT), ";
2745 let m = n.swap_bytes();
2747 assert_eq!(m, ", $swapped, ");
2749 #[stable(feature = "rust1", since = "1.0.0")]
2750 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2752 pub const fn swap_bytes(self) -> Self {
2753 intrinsics::bswap(self as $ActualT) as Self
2758 concat!("Reverses the bit pattern of the integer.
2765 let n = ", $swap_op, stringify!($SelfT), ";
2766 let m = n.reverse_bits();
2768 assert_eq!(m, ", $reversed, ");
2770 #[stable(feature = "reverse_bits", since = "1.37.0")]
2771 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2774 pub const fn reverse_bits(self) -> Self {
2775 intrinsics::bitreverse(self as $ActualT) as Self
2780 concat!("Converts an integer from big endian to the target's endianness.
2782 On big endian this is a no-op. On little endian the bytes are
2790 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2792 if cfg!(target_endian = \"big\") {
2793 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
2795 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
2798 #[stable(feature = "rust1", since = "1.0.0")]
2799 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2801 pub const fn from_be(x: Self) -> Self {
2802 #[cfg(target_endian = "big")]
2806 #[cfg(not(target_endian = "big"))]
2814 concat!("Converts an integer from little endian to the target's endianness.
2816 On little endian this is a no-op. On big endian the bytes are
2824 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2826 if cfg!(target_endian = \"little\") {
2827 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
2829 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
2832 #[stable(feature = "rust1", since = "1.0.0")]
2833 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2835 pub const fn from_le(x: Self) -> Self {
2836 #[cfg(target_endian = "little")]
2840 #[cfg(not(target_endian = "little"))]
2848 concat!("Converts `self` to big endian from the target's endianness.
2850 On big endian this is a no-op. On little endian the bytes are
2858 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2860 if cfg!(target_endian = \"big\") {
2861 assert_eq!(n.to_be(), n)
2863 assert_eq!(n.to_be(), n.swap_bytes())
2866 #[stable(feature = "rust1", since = "1.0.0")]
2867 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2869 pub const fn to_be(self) -> Self { // or not to be?
2870 #[cfg(target_endian = "big")]
2874 #[cfg(not(target_endian = "big"))]
2882 concat!("Converts `self` to little endian from the target's endianness.
2884 On little endian this is a no-op. On big endian the bytes are
2892 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2894 if cfg!(target_endian = \"little\") {
2895 assert_eq!(n.to_le(), n)
2897 assert_eq!(n.to_le(), n.swap_bytes())
2900 #[stable(feature = "rust1", since = "1.0.0")]
2901 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
2903 pub const fn to_le(self) -> Self {
2904 #[cfg(target_endian = "little")]
2908 #[cfg(not(target_endian = "little"))]
2916 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2917 if overflow occurred.
2924 ", $Feature, "assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(1), ",
2925 "Some(", stringify!($SelfT), "::MAX - 1));
2926 assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);", $EndFeature, "
2928 #[stable(feature = "rust1", since = "1.0.0")]
2929 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2930 #[must_use = "this returns the result of the operation, \
2931 without modifying the original"]
2933 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
2934 let (a, b) = self.overflowing_add(rhs);
2935 if b {None} else {Some(a)}
2940 concat!("Checked integer subtraction. Computes `self - rhs`, returning
2941 `None` if overflow occurred.
2948 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
2949 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
2951 #[stable(feature = "rust1", since = "1.0.0")]
2952 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2953 #[must_use = "this returns the result of the operation, \
2954 without modifying the original"]
2956 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
2957 let (a, b) = self.overflowing_sub(rhs);
2958 if b {None} else {Some(a)}
2963 concat!("Checked integer multiplication. Computes `self * rhs`, returning
2964 `None` if overflow occurred.
2971 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
2972 assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);", $EndFeature, "
2974 #[stable(feature = "rust1", since = "1.0.0")]
2975 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2976 #[must_use = "this returns the result of the operation, \
2977 without modifying the original"]
2979 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
2980 let (a, b) = self.overflowing_mul(rhs);
2981 if b {None} else {Some(a)}
2986 concat!("Checked integer division. Computes `self / rhs`, returning `None`
2994 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2995 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2997 #[stable(feature = "rust1", since = "1.0.0")]
2998 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
2999 #[must_use = "this returns the result of the operation, \
3000 without modifying the original"]
3002 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
3005 // SAFETY: div by zero has been checked above and unsigned types have no other
3006 // failure modes for division
3007 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
3013 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
3021 assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));
3022 assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);
3024 #[stable(feature = "euclidean_division", since = "1.38.0")]
3025 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3026 #[must_use = "this returns the result of the operation, \
3027 without modifying the original"]
3029 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
3033 Some(self.div_euclid(rhs))
3040 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
3048 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
3049 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
3051 #[stable(feature = "wrapping", since = "1.7.0")]
3052 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3053 #[must_use = "this returns the result of the operation, \
3054 without modifying the original"]
3056 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
3060 // SAFETY: div by zero has been checked above and unsigned types have no other
3061 // failure modes for division
3062 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
3068 concat!("Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
3076 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
3077 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
3079 #[stable(feature = "euclidean_division", since = "1.38.0")]
3080 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3081 #[must_use = "this returns the result of the operation, \
3082 without modifying the original"]
3084 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
3088 Some(self.rem_euclid(rhs))
3094 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
3097 Note that negating any positive integer will overflow.
3104 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
3105 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
3107 #[stable(feature = "wrapping", since = "1.7.0")]
3108 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3110 pub const fn checked_neg(self) -> Option<Self> {
3111 let (a, b) = self.overflowing_neg();
3112 if b {None} else {Some(a)}
3117 concat!("Checked shift left. Computes `self << rhs`, returning `None`
3118 if `rhs` is larger than or equal to the number of bits in `self`.
3125 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
3126 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
3128 #[stable(feature = "wrapping", since = "1.7.0")]
3129 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3130 #[must_use = "this returns the result of the operation, \
3131 without modifying the original"]
3133 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
3134 let (a, b) = self.overflowing_shl(rhs);
3135 if b {None} else {Some(a)}
3140 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
3141 if `rhs` is larger than or equal to the number of bits in `self`.
3148 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
3149 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
3151 #[stable(feature = "wrapping", since = "1.7.0")]
3152 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
3153 #[must_use = "this returns the result of the operation, \
3154 without modifying the original"]
3156 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
3157 let (a, b) = self.overflowing_shr(rhs);
3158 if b {None} else {Some(a)}
3163 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
3171 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
3172 assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);", $EndFeature, "
3174 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3175 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3176 #[must_use = "this returns the result of the operation, \
3177 without modifying the original"]
3179 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
3180 let mut base = self;
3181 let mut acc: Self = 1;
3185 acc = try_opt!(acc.checked_mul(base));
3188 base = try_opt!(base.checked_mul(base));
3191 // Deal with the final bit of the exponent separately, since
3192 // squaring the base afterwards is not necessary and may cause a
3193 // needless overflow.
3195 acc = try_opt!(acc.checked_mul(base));
3203 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
3204 the numeric bounds instead of overflowing.
3211 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
3212 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
3215 #[stable(feature = "rust1", since = "1.0.0")]
3216 #[must_use = "this returns the result of the operation, \
3217 without modifying the original"]
3218 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
3220 pub const fn saturating_add(self, rhs: Self) -> Self {
3221 intrinsics::saturating_add(self, rhs)
3226 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
3227 at the numeric bounds instead of overflowing.
3234 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
3235 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
3237 #[stable(feature = "rust1", since = "1.0.0")]
3238 #[must_use = "this returns the result of the operation, \
3239 without modifying the original"]
3240 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
3242 pub const fn saturating_sub(self, rhs: Self) -> Self {
3243 intrinsics::saturating_sub(self, rhs)
3248 concat!("Saturating integer multiplication. Computes `self * rhs`,
3249 saturating at the numeric bounds instead of overflowing.
3257 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
3258 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
3259 "::MAX);", $EndFeature, "
3261 #[stable(feature = "wrapping", since = "1.7.0")]
3262 #[rustc_const_unstable(feature = "const_saturating_int_methods", issue = "53718")]
3263 #[must_use = "this returns the result of the operation, \
3264 without modifying the original"]
3266 pub const fn saturating_mul(self, rhs: Self) -> Self {
3267 match self.checked_mul(rhs) {
3269 None => Self::max_value(),
3275 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
3276 saturating at the numeric bounds instead of overflowing.
3284 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
3285 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
3288 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3289 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3290 #[must_use = "this returns the result of the operation, \
3291 without modifying the original"]
3293 pub const fn saturating_pow(self, exp: u32) -> Self {
3294 match self.checked_pow(exp) {
3296 None => Self::max_value(),
3302 concat!("Wrapping (modular) addition. Computes `self + rhs`,
3303 wrapping around at the boundary of the type.
3310 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
3311 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);",
3314 #[stable(feature = "rust1", since = "1.0.0")]
3315 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3316 #[must_use = "this returns the result of the operation, \
3317 without modifying the original"]
3319 pub const fn wrapping_add(self, rhs: Self) -> Self {
3320 intrinsics::wrapping_add(self, rhs)
3325 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
3326 wrapping around at the boundary of the type.
3333 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
3334 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::MAX), 101);",
3337 #[stable(feature = "rust1", since = "1.0.0")]
3338 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3339 #[must_use = "this returns the result of the operation, \
3340 without modifying the original"]
3342 pub const fn wrapping_sub(self, rhs: Self) -> Self {
3343 intrinsics::wrapping_sub(self, rhs)
3347 /// Wrapping (modular) multiplication. Computes `self *
3348 /// rhs`, wrapping around at the boundary of the type.
3354 /// Please note that this example is shared between integer types.
3355 /// Which explains why `u8` is used here.
3358 /// assert_eq!(10u8.wrapping_mul(12), 120);
3359 /// assert_eq!(25u8.wrapping_mul(12), 44);
3361 #[stable(feature = "rust1", since = "1.0.0")]
3362 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3363 #[must_use = "this returns the result of the operation, \
3364 without modifying the original"]
3366 pub const fn wrapping_mul(self, rhs: Self) -> Self {
3367 intrinsics::wrapping_mul(self, rhs)
3371 concat!("Wrapping (modular) division. Computes `self / rhs`.
3372 Wrapped division on unsigned types is just normal division.
3373 There's no way wrapping could ever happen.
3374 This function exists, so that all operations
3375 are accounted for in the wrapping operations.
3382 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
3384 #[stable(feature = "num_wrapping", since = "1.2.0")]
3385 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
3386 #[must_use = "this returns the result of the operation, \
3387 without modifying the original"]
3389 pub const fn wrapping_div(self, rhs: Self) -> Self {
3395 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
3396 Wrapped division on unsigned types is just normal division.
3397 There's no way wrapping could ever happen.
3398 This function exists, so that all operations
3399 are accounted for in the wrapping operations.
3400 Since, for the positive integers, all common
3401 definitions of division are equal, this
3402 is exactly equal to `self.wrapping_div(rhs)`.
3409 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
3411 #[stable(feature = "euclidean_division", since = "1.38.0")]
3412 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3413 #[must_use = "this returns the result of the operation, \
3414 without modifying the original"]
3416 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
3422 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
3423 Wrapped remainder calculation on unsigned types is
3424 just the regular remainder calculation.
3425 There's no way wrapping could ever happen.
3426 This function exists, so that all operations
3427 are accounted for in the wrapping operations.
3434 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
3436 #[stable(feature = "num_wrapping", since = "1.2.0")]
3437 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
3438 #[must_use = "this returns the result of the operation, \
3439 without modifying the original"]
3441 pub const fn wrapping_rem(self, rhs: Self) -> Self {
3447 concat!("Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
3448 Wrapped modulo calculation on unsigned types is
3449 just the regular remainder calculation.
3450 There's no way wrapping could ever happen.
3451 This function exists, so that all operations
3452 are accounted for in the wrapping operations.
3453 Since, for the positive integers, all common
3454 definitions of division are equal, this
3455 is exactly equal to `self.wrapping_rem(rhs)`.
3462 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
3464 #[stable(feature = "euclidean_division", since = "1.38.0")]
3465 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3466 #[must_use = "this returns the result of the operation, \
3467 without modifying the original"]
3469 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
3474 /// Wrapping (modular) negation. Computes `-self`,
3475 /// wrapping around at the boundary of the type.
3477 /// Since unsigned types do not have negative equivalents
3478 /// all applications of this function will wrap (except for `-0`).
3479 /// For values smaller than the corresponding signed type's maximum
3480 /// the result is the same as casting the corresponding signed value.
3481 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
3482 /// `MAX` is the corresponding signed type's maximum.
3488 /// Please note that this example is shared between integer types.
3489 /// Which explains why `i8` is used here.
3492 /// assert_eq!(100i8.wrapping_neg(), -100);
3493 /// assert_eq!((-128i8).wrapping_neg(), -128);
3495 #[stable(feature = "num_wrapping", since = "1.2.0")]
3496 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3498 pub const fn wrapping_neg(self) -> Self {
3499 self.overflowing_neg().0
3503 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
3504 where `mask` removes any high-order bits of `rhs` that
3505 would cause the shift to exceed the bitwidth of the type.
3507 Note that this is *not* the same as a rotate-left; the
3508 RHS of a wrapping shift-left is restricted to the range
3509 of the type, rather than the bits shifted out of the LHS
3510 being returned to the other end. The primitive integer
3511 types all implement a [`rotate_left`](#method.rotate_left) function,
3512 which may be what you want instead.
3519 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
3520 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
3522 #[stable(feature = "num_wrapping", since = "1.2.0")]
3523 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3524 #[must_use = "this returns the result of the operation, \
3525 without modifying the original"]
3527 pub const fn wrapping_shl(self, rhs: u32) -> Self {
3528 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
3531 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
3537 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
3538 where `mask` removes any high-order bits of `rhs` that
3539 would cause the shift to exceed the bitwidth of the type.
3541 Note that this is *not* the same as a rotate-right; the
3542 RHS of a wrapping shift-right is restricted to the range
3543 of the type, rather than the bits shifted out of the LHS
3544 being returned to the other end. The primitive integer
3545 types all implement a [`rotate_right`](#method.rotate_right) function,
3546 which may be what you want instead.
3553 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
3554 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
3556 #[stable(feature = "num_wrapping", since = "1.2.0")]
3557 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3558 #[must_use = "this returns the result of the operation, \
3559 without modifying the original"]
3561 pub const fn wrapping_shr(self, rhs: u32) -> Self {
3562 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
3565 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
3571 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
3572 wrapping around at the boundary of the type.
3579 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
3580 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
3582 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3583 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3584 #[must_use = "this returns the result of the operation, \
3585 without modifying the original"]
3587 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
3588 let mut base = self;
3589 let mut acc: Self = 1;
3593 acc = acc.wrapping_mul(base);
3596 base = base.wrapping_mul(base);
3599 // Deal with the final bit of the exponent separately, since
3600 // squaring the base afterwards is not necessary and may cause a
3601 // needless overflow.
3603 acc = acc.wrapping_mul(base);
3611 concat!("Calculates `self` + `rhs`
3613 Returns a tuple of the addition along with a boolean indicating
3614 whether an arithmetic overflow would occur. If an overflow would
3615 have occurred then the wrapped value is returned.
3623 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
3624 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
3626 #[stable(feature = "wrapping", since = "1.7.0")]
3627 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3628 #[must_use = "this returns the result of the operation, \
3629 without modifying the original"]
3631 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
3632 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
3638 concat!("Calculates `self` - `rhs`
3640 Returns a tuple of the subtraction along with a boolean indicating
3641 whether an arithmetic overflow would occur. If an overflow would
3642 have occurred then the wrapped value is returned.
3650 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
3651 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
3654 #[stable(feature = "wrapping", since = "1.7.0")]
3655 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3656 #[must_use = "this returns the result of the operation, \
3657 without modifying the original"]
3659 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3660 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
3665 /// Calculates the multiplication of `self` and `rhs`.
3667 /// Returns a tuple of the multiplication along with a boolean
3668 /// indicating whether an arithmetic overflow would occur. If an
3669 /// overflow would have occurred then the wrapped value is returned.
3675 /// Please note that this example is shared between integer types.
3676 /// Which explains why `u32` is used here.
3679 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3680 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3682 #[stable(feature = "wrapping", since = "1.7.0")]
3683 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3684 #[must_use = "this returns the result of the operation, \
3685 without modifying the original"]
3687 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3688 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
3693 concat!("Calculates the divisor when `self` is divided by `rhs`.
3695 Returns a tuple of the divisor along with a boolean indicating
3696 whether an arithmetic overflow would occur. Note that for unsigned
3697 integers overflow never occurs, so the second value is always
3702 This function will panic if `rhs` is 0.
3709 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
3712 #[stable(feature = "wrapping", since = "1.7.0")]
3713 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
3714 #[must_use = "this returns the result of the operation, \
3715 without modifying the original"]
3716 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3722 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
3724 Returns a tuple of the divisor along with a boolean indicating
3725 whether an arithmetic overflow would occur. Note that for unsigned
3726 integers overflow never occurs, so the second value is always
3728 Since, for the positive integers, all common
3729 definitions of division are equal, this
3730 is exactly equal to `self.overflowing_div(rhs)`.
3734 This function will panic if `rhs` is 0.
3741 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
3744 #[stable(feature = "euclidean_division", since = "1.38.0")]
3745 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3746 #[must_use = "this returns the result of the operation, \
3747 without modifying the original"]
3748 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
3754 concat!("Calculates the remainder when `self` is divided by `rhs`.
3756 Returns a tuple of the remainder after dividing along with a boolean
3757 indicating whether an arithmetic overflow would occur. Note that for
3758 unsigned integers overflow never occurs, so the second value is
3763 This function will panic if `rhs` is 0.
3770 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3773 #[stable(feature = "wrapping", since = "1.7.0")]
3774 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
3775 #[must_use = "this returns the result of the operation, \
3776 without modifying the original"]
3777 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3783 concat!("Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
3785 Returns a tuple of the modulo after dividing along with a boolean
3786 indicating whether an arithmetic overflow would occur. Note that for
3787 unsigned integers overflow never occurs, so the second value is
3789 Since, for the positive integers, all common
3790 definitions of division are equal, this operation
3791 is exactly equal to `self.overflowing_rem(rhs)`.
3795 This function will panic if `rhs` is 0.
3802 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
3805 #[stable(feature = "euclidean_division", since = "1.38.0")]
3806 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
3807 #[must_use = "this returns the result of the operation, \
3808 without modifying the original"]
3809 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
3815 concat!("Negates self in an overflowing fashion.
3817 Returns `!self + 1` using wrapping operations to return the value
3818 that represents the negation of this unsigned value. Note that for
3819 positive unsigned values overflow always occurs, but negating 0 does
3827 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3828 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3829 ", true));", $EndFeature, "
3832 #[stable(feature = "wrapping", since = "1.7.0")]
3833 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3834 pub const fn overflowing_neg(self) -> (Self, bool) {
3835 ((!self).wrapping_add(1), self != 0)
3840 concat!("Shifts self left by `rhs` bits.
3842 Returns a tuple of the shifted version of self along with a boolean
3843 indicating whether the shift value was larger than or equal to the
3844 number of bits. If the shift value is too large, then value is
3845 masked (N-1) where N is the number of bits, and this value is then
3846 used to perform the shift.
3853 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3854 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3856 #[stable(feature = "wrapping", since = "1.7.0")]
3857 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3858 #[must_use = "this returns the result of the operation, \
3859 without modifying the original"]
3861 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3862 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3867 concat!("Shifts self right by `rhs` bits.
3869 Returns a tuple of the shifted version of self along with a boolean
3870 indicating whether the shift value was larger than or equal to the
3871 number of bits. If the shift value is too large, then value is
3872 masked (N-1) where N is the number of bits, and this value is then
3873 used to perform the shift.
3880 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
3881 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
3883 #[stable(feature = "wrapping", since = "1.7.0")]
3884 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3885 #[must_use = "this returns the result of the operation, \
3886 without modifying the original"]
3888 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3889 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
3894 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3896 Returns a tuple of the exponentiation along with a bool indicating
3897 whether an overflow happened.
3904 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
3905 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
3907 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3908 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3909 #[must_use = "this returns the result of the operation, \
3910 without modifying the original"]
3912 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3913 let mut base = self;
3914 let mut acc: Self = 1;
3915 let mut overflown = false;
3916 // Scratch space for storing results of overflowing_mul.
3921 r = acc.overflowing_mul(base);
3926 r = base.overflowing_mul(base);
3931 // Deal with the final bit of the exponent separately, since
3932 // squaring the base afterwards is not necessary and may cause a
3933 // needless overflow.
3935 r = acc.overflowing_mul(base);
3945 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3952 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
3954 #[stable(feature = "rust1", since = "1.0.0")]
3955 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
3956 #[must_use = "this returns the result of the operation, \
3957 without modifying the original"]
3959 #[rustc_inherit_overflow_checks]
3960 pub const fn pow(self, mut exp: u32) -> Self {
3961 let mut base = self;
3972 // Deal with the final bit of the exponent separately, since
3973 // squaring the base afterwards is not necessary and may cause a
3974 // needless overflow.
3984 concat!("Performs Euclidean division.
3986 Since, for the positive integers, all common
3987 definitions of division are equal, this
3988 is exactly equal to `self / rhs`.
3992 This function will panic if `rhs` is 0.
3999 assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type
4001 #[stable(feature = "euclidean_division", since = "1.38.0")]
4002 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
4003 #[must_use = "this returns the result of the operation, \
4004 without modifying the original"]
4006 #[rustc_inherit_overflow_checks]
4007 pub const fn div_euclid(self, rhs: Self) -> Self {
4014 concat!("Calculates the least remainder of `self (mod rhs)`.
4016 Since, for the positive integers, all common
4017 definitions of division are equal, this
4018 is exactly equal to `self % rhs`.
4022 This function will panic if `rhs` is 0.
4029 assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type
4031 #[stable(feature = "euclidean_division", since = "1.38.0")]
4032 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
4033 #[must_use = "this returns the result of the operation, \
4034 without modifying the original"]
4036 #[rustc_inherit_overflow_checks]
4037 pub const fn rem_euclid(self, rhs: Self) -> Self {
4043 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
4050 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
4051 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
4053 #[stable(feature = "rust1", since = "1.0.0")]
4054 #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
4056 pub const fn is_power_of_two(self) -> bool {
4057 self.count_ones() == 1
4061 // Returns one less than next power of two.
4062 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
4064 // 8u8.one_less_than_next_power_of_two() == 7
4065 // 6u8.one_less_than_next_power_of_two() == 7
4067 // This method cannot overflow, as in the `next_power_of_two`
4068 // overflow cases it instead ends up returning the maximum value
4069 // of the type, and can return 0 for 0.
4071 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4072 const fn one_less_than_next_power_of_two(self) -> Self {
4073 if self <= 1 { return 0; }
4076 // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros.
4077 // That means the shift is always in-bounds, and some processors
4078 // (such as intel pre-haswell) have more efficient ctlz
4079 // intrinsics when the argument is non-zero.
4080 let z = unsafe { intrinsics::ctlz_nonzero(p) };
4081 <$SelfT>::max_value() >> z
4085 concat!("Returns the smallest power of two greater than or equal to `self`.
4087 When return value overflows (i.e., `self > (1 << (N-1))` for type
4088 `uN`), it panics in debug mode and return value is wrapped to 0 in
4089 release mode (the only situation in which method can return 0).
4096 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
4097 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
4099 #[stable(feature = "rust1", since = "1.0.0")]
4100 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4102 #[rustc_inherit_overflow_checks]
4103 pub const fn next_power_of_two(self) -> Self {
4104 self.one_less_than_next_power_of_two() + 1
4109 concat!("Returns the smallest power of two greater than or equal to `n`. If
4110 the next power of two is greater than the type's maximum value,
4111 `None` is returned, otherwise the power of two is wrapped in `Some`.
4118 ", $Feature, "assert_eq!(2", stringify!($SelfT),
4119 ".checked_next_power_of_two(), Some(2));
4120 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
4121 assert_eq!(", stringify!($SelfT), "::MAX.checked_next_power_of_two(), None);",
4125 #[stable(feature = "rust1", since = "1.0.0")]
4126 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4127 pub const fn checked_next_power_of_two(self) -> Option<Self> {
4128 self.one_less_than_next_power_of_two().checked_add(1)
4133 concat!("Returns the smallest power of two greater than or equal to `n`. If
4134 the next power of two is greater than the type's maximum value,
4135 the return value is wrapped to `0`.
4142 #![feature(wrapping_next_power_of_two)]
4144 assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);
4145 assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);
4146 assert_eq!(", stringify!($SelfT), "::MAX.wrapping_next_power_of_two(), 0);",
4149 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
4150 reason = "needs decision on wrapping behaviour")]
4151 #[rustc_const_unstable(feature = "const_int_pow", issue = "53718")]
4152 pub const fn wrapping_next_power_of_two(self) -> Self {
4153 self.one_less_than_next_power_of_two().wrapping_add(1)
4158 concat!("Return the memory representation of this integer as a byte array in
4159 big-endian (network) byte order.
4166 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
4167 assert_eq!(bytes, ", $be_bytes, ");
4169 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4170 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4172 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
4173 self.to_be().to_ne_bytes()
4178 concat!("Return the memory representation of this integer as a byte array in
4179 little-endian byte order.
4186 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
4187 assert_eq!(bytes, ", $le_bytes, ");
4189 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4190 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4192 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
4193 self.to_le().to_ne_bytes()
4199 Return the memory representation of this integer as a byte array in
4202 As the target platform's native endianness is used, portable code
4203 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
4208 [`to_be_bytes`]: #method.to_be_bytes
4209 [`to_le_bytes`]: #method.to_le_bytes
4214 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
4217 if cfg!(target_endian = \"big\") {
4224 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4225 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4226 // SAFETY: const sound because integers are plain old datatypes so we can always
4227 // transmute them to arrays of bytes
4228 #[allow_internal_unstable(const_fn_union)]
4230 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
4234 bytes: [u8; mem::size_of::<$SelfT>()],
4236 // SAFETY: integers are plain old datatypes so we can always transmute them to
4238 unsafe { Bytes { val: self }.bytes }
4243 concat!("Create an integer value from its representation as a byte array in
4251 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
4252 assert_eq!(value, ", $swap_op, ");
4255 When starting from a slice rather than an array, fallible conversion APIs can be used:
4258 use std::convert::TryInto;
4260 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4261 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4263 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
4266 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4267 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4269 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4270 Self::from_be(Self::from_ne_bytes(bytes))
4276 Create an integer value from its representation as a byte array in
4284 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
4285 assert_eq!(value, ", $swap_op, ");
4288 When starting from a slice rather than an array, fallible conversion APIs can be used:
4291 use std::convert::TryInto;
4293 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4294 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4296 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
4299 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4300 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4302 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4303 Self::from_le(Self::from_ne_bytes(bytes))
4308 concat!("Create an integer value from its memory representation as a byte
4309 array in native endianness.
4311 As the target platform's native endianness is used, portable code
4312 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
4313 appropriate instead.
4315 [`from_be_bytes`]: #method.from_be_bytes
4316 [`from_le_bytes`]: #method.from_le_bytes
4323 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
4328 assert_eq!(value, ", $swap_op, ");
4331 When starting from a slice rather than an array, fallible conversion APIs can be used:
4334 use std::convert::TryInto;
4336 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
4337 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
4339 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
4342 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4343 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
4344 // SAFETY: const sound because integers are plain old datatypes so we can always
4345 // transmute to them
4346 #[allow_internal_unstable(const_fn_union)]
4348 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4352 bytes: [u8; mem::size_of::<$SelfT>()],
4354 // SAFETY: integers are plain old datatypes so we can always transmute to them
4355 unsafe { Bytes { bytes }.val }
4360 concat!("**This method is soft-deprecated.**
4362 Although using it won’t cause compilation warning,
4363 new code should use [`", stringify!($SelfT), "::MIN", "`](#associatedconstant.MIN) instead.
4365 Returns the smallest value that can be represented by this integer type."),
4366 #[stable(feature = "rust1", since = "1.0.0")]
4369 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
4370 pub const fn min_value() -> Self { Self::MIN }
4374 concat!("**This method is soft-deprecated.**
4376 Although using it won’t cause compilation warning,
4377 new code should use [`", stringify!($SelfT), "::MAX", "`](#associatedconstant.MAX) instead.
4379 Returns the largest value that can be represented by this integer type."),
4380 #[stable(feature = "rust1", since = "1.0.0")]
4383 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
4384 pub const fn max_value() -> Self { Self::MAX }
4391 uint_impl! { u8, u8, 8, 255, "", "", 2, "0x82", "0xa", "0x12", "0x12", "0x48", "[0x12]",
4394 /// Checks if the value is within the ASCII range.
4399 /// let ascii = 97u8;
4400 /// let non_ascii = 150u8;
4402 /// assert!(ascii.is_ascii());
4403 /// assert!(!non_ascii.is_ascii());
4405 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4406 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.43.0")]
4408 pub const fn is_ascii(&self) -> bool {
4412 /// Makes a copy of the value in its ASCII upper case equivalent.
4414 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4415 /// but non-ASCII letters are unchanged.
4417 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
4422 /// let lowercase_a = 97u8;
4424 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
4427 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
4428 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4430 pub fn to_ascii_uppercase(&self) -> u8 {
4431 // Unset the fifth bit if this is a lowercase letter
4432 *self & !((self.is_ascii_lowercase() as u8) << 5)
4435 /// Makes a copy of the value in its ASCII lower case equivalent.
4437 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4438 /// but non-ASCII letters are unchanged.
4440 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
4445 /// let uppercase_a = 65u8;
4447 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
4450 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
4451 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4453 pub fn to_ascii_lowercase(&self) -> u8 {
4454 // Set the fifth bit if this is an uppercase letter
4455 *self | ((self.is_ascii_uppercase() as u8) << 5)
4458 /// Checks that two values are an ASCII case-insensitive match.
4460 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
4465 /// let lowercase_a = 97u8;
4466 /// let uppercase_a = 65u8;
4468 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
4470 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4472 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
4473 self.to_ascii_lowercase() == other.to_ascii_lowercase()
4476 /// Converts this value to its ASCII upper case equivalent in-place.
4478 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4479 /// but non-ASCII letters are unchanged.
4481 /// To return a new uppercased value without modifying the existing one, use
4482 /// [`to_ascii_uppercase`].
4487 /// let mut byte = b'a';
4489 /// byte.make_ascii_uppercase();
4491 /// assert_eq!(b'A', byte);
4494 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
4495 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4497 pub fn make_ascii_uppercase(&mut self) {
4498 *self = self.to_ascii_uppercase();
4501 /// Converts this value to its ASCII lower case equivalent in-place.
4503 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4504 /// but non-ASCII letters are unchanged.
4506 /// To return a new lowercased value without modifying the existing one, use
4507 /// [`to_ascii_lowercase`].
4512 /// let mut byte = b'A';
4514 /// byte.make_ascii_lowercase();
4516 /// assert_eq!(b'a', byte);
4519 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
4520 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4522 pub fn make_ascii_lowercase(&mut self) {
4523 *self = self.to_ascii_lowercase();
4526 /// Checks if the value is an ASCII alphabetic character:
4528 /// - U+0041 'A' ..= U+005A 'Z', or
4529 /// - U+0061 'a' ..= U+007A 'z'.
4534 /// let uppercase_a = b'A';
4535 /// let uppercase_g = b'G';
4538 /// let zero = b'0';
4539 /// let percent = b'%';
4540 /// let space = b' ';
4542 /// let esc = 0x1b_u8;
4544 /// assert!(uppercase_a.is_ascii_alphabetic());
4545 /// assert!(uppercase_g.is_ascii_alphabetic());
4546 /// assert!(a.is_ascii_alphabetic());
4547 /// assert!(g.is_ascii_alphabetic());
4548 /// assert!(!zero.is_ascii_alphabetic());
4549 /// assert!(!percent.is_ascii_alphabetic());
4550 /// assert!(!space.is_ascii_alphabetic());
4551 /// assert!(!lf.is_ascii_alphabetic());
4552 /// assert!(!esc.is_ascii_alphabetic());
4554 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4555 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4557 pub const fn is_ascii_alphabetic(&self) -> bool {
4558 matches!(*self, b'A'..=b'Z' | b'a'..=b'z')
4561 /// Checks if the value is an ASCII uppercase character:
4562 /// U+0041 'A' ..= U+005A 'Z'.
4567 /// let uppercase_a = b'A';
4568 /// let uppercase_g = b'G';
4571 /// let zero = b'0';
4572 /// let percent = b'%';
4573 /// let space = b' ';
4575 /// let esc = 0x1b_u8;
4577 /// assert!(uppercase_a.is_ascii_uppercase());
4578 /// assert!(uppercase_g.is_ascii_uppercase());
4579 /// assert!(!a.is_ascii_uppercase());
4580 /// assert!(!g.is_ascii_uppercase());
4581 /// assert!(!zero.is_ascii_uppercase());
4582 /// assert!(!percent.is_ascii_uppercase());
4583 /// assert!(!space.is_ascii_uppercase());
4584 /// assert!(!lf.is_ascii_uppercase());
4585 /// assert!(!esc.is_ascii_uppercase());
4587 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4588 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4590 pub const fn is_ascii_uppercase(&self) -> bool {
4591 matches!(*self, b'A'..=b'Z')
4594 /// Checks if the value is an ASCII lowercase character:
4595 /// U+0061 'a' ..= U+007A 'z'.
4600 /// let uppercase_a = b'A';
4601 /// let uppercase_g = b'G';
4604 /// let zero = b'0';
4605 /// let percent = b'%';
4606 /// let space = b' ';
4608 /// let esc = 0x1b_u8;
4610 /// assert!(!uppercase_a.is_ascii_lowercase());
4611 /// assert!(!uppercase_g.is_ascii_lowercase());
4612 /// assert!(a.is_ascii_lowercase());
4613 /// assert!(g.is_ascii_lowercase());
4614 /// assert!(!zero.is_ascii_lowercase());
4615 /// assert!(!percent.is_ascii_lowercase());
4616 /// assert!(!space.is_ascii_lowercase());
4617 /// assert!(!lf.is_ascii_lowercase());
4618 /// assert!(!esc.is_ascii_lowercase());
4620 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4621 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4623 pub const fn is_ascii_lowercase(&self) -> bool {
4624 matches!(*self, b'a'..=b'z')
4627 /// Checks if the value is an ASCII alphanumeric character:
4629 /// - U+0041 'A' ..= U+005A 'Z', or
4630 /// - U+0061 'a' ..= U+007A 'z', or
4631 /// - U+0030 '0' ..= U+0039 '9'.
4636 /// let uppercase_a = b'A';
4637 /// let uppercase_g = b'G';
4640 /// let zero = b'0';
4641 /// let percent = b'%';
4642 /// let space = b' ';
4644 /// let esc = 0x1b_u8;
4646 /// assert!(uppercase_a.is_ascii_alphanumeric());
4647 /// assert!(uppercase_g.is_ascii_alphanumeric());
4648 /// assert!(a.is_ascii_alphanumeric());
4649 /// assert!(g.is_ascii_alphanumeric());
4650 /// assert!(zero.is_ascii_alphanumeric());
4651 /// assert!(!percent.is_ascii_alphanumeric());
4652 /// assert!(!space.is_ascii_alphanumeric());
4653 /// assert!(!lf.is_ascii_alphanumeric());
4654 /// assert!(!esc.is_ascii_alphanumeric());
4656 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4657 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4659 pub const fn is_ascii_alphanumeric(&self) -> bool {
4660 matches!(*self, b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z')
4663 /// Checks if the value is an ASCII decimal digit:
4664 /// U+0030 '0' ..= U+0039 '9'.
4669 /// let uppercase_a = b'A';
4670 /// let uppercase_g = b'G';
4673 /// let zero = b'0';
4674 /// let percent = b'%';
4675 /// let space = b' ';
4677 /// let esc = 0x1b_u8;
4679 /// assert!(!uppercase_a.is_ascii_digit());
4680 /// assert!(!uppercase_g.is_ascii_digit());
4681 /// assert!(!a.is_ascii_digit());
4682 /// assert!(!g.is_ascii_digit());
4683 /// assert!(zero.is_ascii_digit());
4684 /// assert!(!percent.is_ascii_digit());
4685 /// assert!(!space.is_ascii_digit());
4686 /// assert!(!lf.is_ascii_digit());
4687 /// assert!(!esc.is_ascii_digit());
4689 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4690 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4692 pub const fn is_ascii_digit(&self) -> bool {
4693 matches!(*self, b'0'..=b'9')
4696 /// Checks if the value is an ASCII hexadecimal digit:
4698 /// - U+0030 '0' ..= U+0039 '9', or
4699 /// - U+0041 'A' ..= U+0046 'F', or
4700 /// - U+0061 'a' ..= U+0066 'f'.
4705 /// let uppercase_a = b'A';
4706 /// let uppercase_g = b'G';
4709 /// let zero = b'0';
4710 /// let percent = b'%';
4711 /// let space = b' ';
4713 /// let esc = 0x1b_u8;
4715 /// assert!(uppercase_a.is_ascii_hexdigit());
4716 /// assert!(!uppercase_g.is_ascii_hexdigit());
4717 /// assert!(a.is_ascii_hexdigit());
4718 /// assert!(!g.is_ascii_hexdigit());
4719 /// assert!(zero.is_ascii_hexdigit());
4720 /// assert!(!percent.is_ascii_hexdigit());
4721 /// assert!(!space.is_ascii_hexdigit());
4722 /// assert!(!lf.is_ascii_hexdigit());
4723 /// assert!(!esc.is_ascii_hexdigit());
4725 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4726 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4728 pub const fn is_ascii_hexdigit(&self) -> bool {
4729 matches!(*self, b'0'..=b'9' | b'A'..=b'F' | b'a'..=b'f')
4732 /// Checks if the value is an ASCII punctuation character:
4734 /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
4735 /// - U+003A ..= U+0040 `: ; < = > ? @`, or
4736 /// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
4737 /// - U+007B ..= U+007E `{ | } ~`
4742 /// let uppercase_a = b'A';
4743 /// let uppercase_g = b'G';
4746 /// let zero = b'0';
4747 /// let percent = b'%';
4748 /// let space = b' ';
4750 /// let esc = 0x1b_u8;
4752 /// assert!(!uppercase_a.is_ascii_punctuation());
4753 /// assert!(!uppercase_g.is_ascii_punctuation());
4754 /// assert!(!a.is_ascii_punctuation());
4755 /// assert!(!g.is_ascii_punctuation());
4756 /// assert!(!zero.is_ascii_punctuation());
4757 /// assert!(percent.is_ascii_punctuation());
4758 /// assert!(!space.is_ascii_punctuation());
4759 /// assert!(!lf.is_ascii_punctuation());
4760 /// assert!(!esc.is_ascii_punctuation());
4762 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4763 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4765 pub const fn is_ascii_punctuation(&self) -> bool {
4766 matches!(*self, b'!'..=b'/' | b':'..=b'@' | b'['..=b'`' | b'{'..=b'~')
4769 /// Checks if the value is an ASCII graphic character:
4770 /// U+0021 '!' ..= U+007E '~'.
4775 /// let uppercase_a = b'A';
4776 /// let uppercase_g = b'G';
4779 /// let zero = b'0';
4780 /// let percent = b'%';
4781 /// let space = b' ';
4783 /// let esc = 0x1b_u8;
4785 /// assert!(uppercase_a.is_ascii_graphic());
4786 /// assert!(uppercase_g.is_ascii_graphic());
4787 /// assert!(a.is_ascii_graphic());
4788 /// assert!(g.is_ascii_graphic());
4789 /// assert!(zero.is_ascii_graphic());
4790 /// assert!(percent.is_ascii_graphic());
4791 /// assert!(!space.is_ascii_graphic());
4792 /// assert!(!lf.is_ascii_graphic());
4793 /// assert!(!esc.is_ascii_graphic());
4795 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4796 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4798 pub const fn is_ascii_graphic(&self) -> bool {
4799 matches!(*self, b'!'..=b'~')
4802 /// Checks if the value is an ASCII whitespace character:
4803 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
4804 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
4806 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
4807 /// whitespace][infra-aw]. There are several other definitions in
4808 /// wide use. For instance, [the POSIX locale][pct] includes
4809 /// U+000B VERTICAL TAB as well as all the above characters,
4810 /// but—from the very same specification—[the default rule for
4811 /// "field splitting" in the Bourne shell][bfs] considers *only*
4812 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
4814 /// If you are writing a program that will process an existing
4815 /// file format, check what that format's definition of whitespace is
4816 /// before using this function.
4818 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
4819 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
4820 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
4825 /// let uppercase_a = b'A';
4826 /// let uppercase_g = b'G';
4829 /// let zero = b'0';
4830 /// let percent = b'%';
4831 /// let space = b' ';
4833 /// let esc = 0x1b_u8;
4835 /// assert!(!uppercase_a.is_ascii_whitespace());
4836 /// assert!(!uppercase_g.is_ascii_whitespace());
4837 /// assert!(!a.is_ascii_whitespace());
4838 /// assert!(!g.is_ascii_whitespace());
4839 /// assert!(!zero.is_ascii_whitespace());
4840 /// assert!(!percent.is_ascii_whitespace());
4841 /// assert!(space.is_ascii_whitespace());
4842 /// assert!(lf.is_ascii_whitespace());
4843 /// assert!(!esc.is_ascii_whitespace());
4845 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4846 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4848 pub const fn is_ascii_whitespace(&self) -> bool {
4849 matches!(*self, b'\t' | b'\n' | b'\x0C' | b'\r' | b' ')
4852 /// Checks if the value is an ASCII control character:
4853 /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
4854 /// Note that most ASCII whitespace characters are control
4855 /// characters, but SPACE is not.
4860 /// let uppercase_a = b'A';
4861 /// let uppercase_g = b'G';
4864 /// let zero = b'0';
4865 /// let percent = b'%';
4866 /// let space = b' ';
4868 /// let esc = 0x1b_u8;
4870 /// assert!(!uppercase_a.is_ascii_control());
4871 /// assert!(!uppercase_g.is_ascii_control());
4872 /// assert!(!a.is_ascii_control());
4873 /// assert!(!g.is_ascii_control());
4874 /// assert!(!zero.is_ascii_control());
4875 /// assert!(!percent.is_ascii_control());
4876 /// assert!(!space.is_ascii_control());
4877 /// assert!(lf.is_ascii_control());
4878 /// assert!(esc.is_ascii_control());
4880 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4881 #[rustc_const_unstable(feature = "const_ascii_ctype_on_intrinsics", issue = "68983")]
4883 pub const fn is_ascii_control(&self) -> bool {
4884 matches!(*self, b'\0'..=b'\x1F' | b'\x7F')
4890 uint_impl! { u16, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4891 "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
4896 uint_impl! { u32, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4897 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]", "", "" }
4902 uint_impl! { u64, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4903 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4904 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4905 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
4911 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "", 16,
4912 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
4913 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
4914 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
4915 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4916 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
4917 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
4921 #[cfg(target_pointer_width = "16")]
4924 uint_impl! { usize, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4925 "[0x34, 0x12]", "[0x12, 0x34]",
4926 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4928 #[cfg(target_pointer_width = "32")]
4931 uint_impl! { usize, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4932 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]",
4933 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4936 #[cfg(target_pointer_width = "64")]
4939 uint_impl! { usize, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4940 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4941 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4942 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
4943 usize_isize_to_xe_bytes_doc!(), usize_isize_from_xe_bytes_doc!() }
4946 /// A classification of floating point numbers.
4948 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
4949 /// their documentation for more.
4951 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
4952 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
4957 /// use std::num::FpCategory;
4959 /// let num = 12.4_f32;
4960 /// let inf = f32::INFINITY;
4961 /// let zero = 0f32;
4962 /// let sub: f32 = 1.1754942e-38;
4963 /// let nan = f32::NAN;
4965 /// assert_eq!(num.classify(), FpCategory::Normal);
4966 /// assert_eq!(inf.classify(), FpCategory::Infinite);
4967 /// assert_eq!(zero.classify(), FpCategory::Zero);
4968 /// assert_eq!(nan.classify(), FpCategory::Nan);
4969 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
4971 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
4972 #[stable(feature = "rust1", since = "1.0.0")]
4973 pub enum FpCategory {
4974 /// "Not a Number", often obtained by dividing by zero.
4975 #[stable(feature = "rust1", since = "1.0.0")]
4978 /// Positive or negative infinity.
4979 #[stable(feature = "rust1", since = "1.0.0")]
4982 /// Positive or negative zero.
4983 #[stable(feature = "rust1", since = "1.0.0")]
4986 /// De-normalized floating point representation (less precise than `Normal`).
4987 #[stable(feature = "rust1", since = "1.0.0")]
4990 /// A regular floating point number.
4991 #[stable(feature = "rust1", since = "1.0.0")]
4995 macro_rules! from_str_radix_int_impl {
4997 #[stable(feature = "rust1", since = "1.0.0")]
4998 impl FromStr for $t {
4999 type Err = ParseIntError;
5000 fn from_str(src: &str) -> Result<Self, ParseIntError> {
5001 from_str_radix(src, 10)
5006 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
5008 /// The error type returned when a checked integral type conversion fails.
5009 #[stable(feature = "try_from", since = "1.34.0")]
5010 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
5011 pub struct TryFromIntError(pub(crate) ());
5013 impl TryFromIntError {
5015 feature = "int_error_internals",
5016 reason = "available through Error trait and this method should \
5017 not be exposed publicly",
5021 pub fn __description(&self) -> &str {
5022 "out of range integral type conversion attempted"
5026 #[stable(feature = "try_from", since = "1.34.0")]
5027 impl fmt::Display for TryFromIntError {
5028 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
5029 self.__description().fmt(fmt)
5033 #[stable(feature = "try_from", since = "1.34.0")]
5034 impl From<Infallible> for TryFromIntError {
5035 fn from(x: Infallible) -> TryFromIntError {
5040 #[unstable(feature = "never_type", issue = "35121")]
5041 impl From<!> for TryFromIntError {
5042 fn from(never: !) -> TryFromIntError {
5043 // Match rather than coerce to make sure that code like
5044 // `From<Infallible> for TryFromIntError` above will keep working
5045 // when `Infallible` becomes an alias to `!`.
5051 trait FromStrRadixHelper: PartialOrd + Copy {
5052 fn min_value() -> Self;
5053 fn max_value() -> Self;
5054 fn from_u32(u: u32) -> Self;
5055 fn checked_mul(&self, other: u32) -> Option<Self>;
5056 fn checked_sub(&self, other: u32) -> Option<Self>;
5057 fn checked_add(&self, other: u32) -> Option<Self>;
5061 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
5063 fn min_value() -> Self { Self::min_value() }
5065 fn max_value() -> Self { Self::max_value() }
5067 fn from_u32(u: u32) -> Self { u as Self }
5069 fn checked_mul(&self, other: u32) -> Option<Self> {
5070 Self::checked_mul(*self, other as Self)
5073 fn checked_sub(&self, other: u32) -> Option<Self> {
5074 Self::checked_sub(*self, other as Self)
5077 fn checked_add(&self, other: u32) -> Option<Self> {
5078 Self::checked_add(*self, other as Self)
5082 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
5084 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
5085 use self::IntErrorKind::*;
5086 use self::ParseIntError as PIE;
5089 radix >= 2 && radix <= 36,
5090 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
5095 return Err(PIE { kind: Empty });
5098 let is_signed_ty = T::from_u32(0) > T::min_value();
5100 // all valid digits are ascii, so we will just iterate over the utf8 bytes
5101 // and cast them to chars. .to_digit() will safely return None for anything
5102 // other than a valid ascii digit for the given radix, including the first-byte
5103 // of multi-byte sequences
5104 let src = src.as_bytes();
5106 let (is_positive, digits) = match src[0] {
5107 b'+' => (true, &src[1..]),
5108 b'-' if is_signed_ty => (false, &src[1..]),
5112 if digits.is_empty() {
5113 return Err(PIE { kind: Empty });
5116 let mut result = T::from_u32(0);
5118 // The number is positive
5120 let x = match (c as char).to_digit(radix) {
5122 None => return Err(PIE { kind: InvalidDigit }),
5124 result = match result.checked_mul(radix) {
5125 Some(result) => result,
5126 None => return Err(PIE { kind: Overflow }),
5128 result = match result.checked_add(x) {
5129 Some(result) => result,
5130 None => return Err(PIE { kind: Overflow }),
5134 // The number is negative
5136 let x = match (c as char).to_digit(radix) {
5138 None => return Err(PIE { kind: InvalidDigit }),
5140 result = match result.checked_mul(radix) {
5141 Some(result) => result,
5142 None => return Err(PIE { kind: Underflow }),
5144 result = match result.checked_sub(x) {
5145 Some(result) => result,
5146 None => return Err(PIE { kind: Underflow }),
5153 /// An error which can be returned when parsing an integer.
5155 /// This error is used as the error type for the `from_str_radix()` functions
5156 /// on the primitive integer types, such as [`i8::from_str_radix`].
5158 /// # Potential causes
5160 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
5161 /// in the string e.g., when it is obtained from the standard input.
5162 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
5164 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
5165 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
5166 #[derive(Debug, Clone, PartialEq, Eq)]
5167 #[stable(feature = "rust1", since = "1.0.0")]
5168 pub struct ParseIntError {
5172 /// Enum to store the various types of errors that can cause parsing an integer to fail.
5174 feature = "int_error_matching",
5175 reason = "it can be useful to match errors when making error messages \
5176 for integer parsing",
5179 #[derive(Debug, Clone, PartialEq, Eq)]
5181 pub enum IntErrorKind {
5182 /// Value being parsed is empty.
5184 /// Among other causes, this variant will be constructed when parsing an empty string.
5186 /// Contains an invalid digit.
5188 /// Among other causes, this variant will be constructed when parsing a string that
5189 /// contains a letter.
5191 /// Integer is too large to store in target integer type.
5193 /// Integer is too small to store in target integer type.
5197 /// This variant will be emitted when the parsing string has a value of zero, which
5198 /// would be illegal for non-zero types.
5202 impl ParseIntError {
5203 /// Outputs the detailed cause of parsing an integer failing.
5205 feature = "int_error_matching",
5206 reason = "it can be useful to match errors when making error messages \
5207 for integer parsing",
5210 pub fn kind(&self) -> &IntErrorKind {
5214 feature = "int_error_internals",
5215 reason = "available through Error trait and this method should \
5216 not be exposed publicly",
5220 pub fn __description(&self) -> &str {
5222 IntErrorKind::Empty => "cannot parse integer from empty string",
5223 IntErrorKind::InvalidDigit => "invalid digit found in string",
5224 IntErrorKind::Overflow => "number too large to fit in target type",
5225 IntErrorKind::Underflow => "number too small to fit in target type",
5226 IntErrorKind::Zero => "number would be zero for non-zero type",
5231 #[stable(feature = "rust1", since = "1.0.0")]
5232 impl fmt::Display for ParseIntError {
5233 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5234 self.__description().fmt(f)
5238 #[stable(feature = "rust1", since = "1.0.0")]
5239 pub use crate::num::dec2flt::ParseFloatError;