1 // ignore-tidy-filelength
3 //! Numeric traits and functions for the built-in numeric types.
5 #![stable(feature = "rust1", since = "1.0.0")]
7 use crate::convert
::{TryFrom, Infallible}
;
12 use crate::str::FromStr
;
14 macro_rules
! impl_nonzero_fmt
{
15 ( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
18 impl fmt
::$Trait
for $Ty
{
20 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
28 macro_rules
! doc_comment
{
29 ($x
:expr
, $
($tt
:tt
)*) => {
35 macro_rules
! nonzero_integers
{
36 ( $
( #[$stability: meta] $Ty: ident($Int: ty); )+ ) => {
39 concat
!("An integer that is known not to equal zero.
41 This enables some memory layout optimization.
42 For example, `Option<", stringify
!($Ty
), ">` is the same size as `", stringify
!($Int
), "`:
45 use std::mem::size_of;
46 assert_eq!(size_of::<Option<core::num::", stringify
!($Ty
), ">>(), size_of::<", stringify
!($Int
),
50 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
52 #[rustc_layout_scalar_valid_range_start(1)]
57 /// Creates a non-zero without checking the value.
61 /// The value must not be zero.
64 pub const unsafe fn new_unchecked(n
: $Int
) -> Self {
68 /// Creates a non-zero if the given value is not zero.
71 pub fn new(n
: $Int
) -> Option
<Self> {
73 Some(unsafe { $Ty(n) }
)
79 /// Returns the value as a primitive type.
82 pub const fn get(self) -> $Int
{
88 #[stable(feature = "from_nonzero", since = "1.31.0")]
89 impl From
<$Ty
> for $Int
{
90 fn from(nonzero
: $Ty
) -> Self {
96 #[$stability] (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
103 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU8(u8);
104 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU16(u16);
105 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU32(u32);
106 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU64(u64);
107 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU128(u128);
108 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroUsize(usize);
109 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI8(i8);
110 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI16(i16);
111 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI32(i32);
112 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI64(i64);
113 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI128(i128);
114 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroIsize(isize);
117 macro_rules
! from_str_radix_nzint_impl
{
119 #[stable(feature = "nonzero_parse", since = "1.35.0")]
120 impl FromStr
for $t
{
121 type Err
= ParseIntError
;
122 fn from_str(src
: &str) -> Result
<Self, Self::Err
> {
123 Self::new(from_str_radix(src
, 10)?
)
124 .ok_or(ParseIntError
{
125 kind
: IntErrorKind
::Zero
132 from_str_radix_nzint_impl
! { NonZeroU8 NonZeroU16 NonZeroU32 NonZeroU64 NonZeroU128 NonZeroUsize
133 NonZeroI8 NonZeroI16 NonZeroI32 NonZeroI64 NonZeroI128 NonZeroIsize
}
135 /// Provides intentionally-wrapped arithmetic on `T`.
137 /// Operations like `+` on `u32` values is intended to never overflow,
138 /// and in some debug configurations overflow is detected and results
139 /// in a panic. While most arithmetic falls into this category, some
140 /// code explicitly expects and relies upon modular arithmetic (e.g.,
143 /// Wrapping arithmetic can be achieved either through methods like
144 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
145 /// all standard arithmetic operations on the underlying value are
146 /// intended to have wrapping semantics.
148 /// The underlying value can be retrieved through the `.0` index of the
149 /// `Wrapping` tuple.
154 /// use std::num::Wrapping;
156 /// let zero = Wrapping(0u32);
157 /// let one = Wrapping(1u32);
159 /// assert_eq!(std::u32::MAX, (zero - one).0);
161 #[stable(feature = "rust1", since = "1.0.0")]
162 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
164 pub struct Wrapping
<T
>(#[stable(feature = "rust1", since = "1.0.0")]
167 #[stable(feature = "rust1", since = "1.0.0")]
168 impl<T
: fmt
::Debug
> fmt
::Debug
for Wrapping
<T
> {
169 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
174 #[stable(feature = "wrapping_display", since = "1.10.0")]
175 impl<T
: fmt
::Display
> fmt
::Display
for Wrapping
<T
> {
176 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
181 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
182 impl<T
: fmt
::Binary
> fmt
::Binary
for Wrapping
<T
> {
183 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
188 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
189 impl<T
: fmt
::Octal
> fmt
::Octal
for Wrapping
<T
> {
190 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
195 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
196 impl<T
: fmt
::LowerHex
> fmt
::LowerHex
for Wrapping
<T
> {
197 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
202 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
203 impl<T
: fmt
::UpperHex
> fmt
::UpperHex
for Wrapping
<T
> {
204 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
209 // All these modules are technically private and only exposed for coretests:
217 macro_rules
! usize_isize_to_xe_bytes_doc
{
220 **Note**: This function returns an array of length 2, 4 or 8 bytes
221 depending on the target pointer size.
227 macro_rules
! usize_isize_from_xe_bytes_doc
{
230 **Note**: This function takes an array of length 2, 4 or 8 bytes
231 depending on the target pointer size.
236 // `Int` + `SignedInt` implemented for signed integers
237 macro_rules
! int_impl
{
238 ($SelfT
:ty
, $ActualT
:ident
, $UnsignedT
:ty
, $BITS
:expr
, $Min
:expr
, $Max
:expr
, $Feature
:expr
,
239 $EndFeature
:expr
, $rot
:expr
, $rot_op
:expr
, $rot_result
:expr
, $swap_op
:expr
, $swapped
:expr
,
240 $reversed
:expr
, $le_bytes
:expr
, $be_bytes
:expr
,
241 $to_xe_bytes_doc
:expr
, $from_xe_bytes_doc
:expr
) => {
243 concat
!("Returns the smallest value that can be represented by this integer type.
250 ", $Feature
, "assert_eq!(", stringify
!($SelfT
), "::min_value(), ", stringify
!($Min
), ");",
253 #[stable(feature = "rust1", since = "1.0.0")]
256 pub const fn min_value() -> Self {
257 !0 ^
((!0 as $UnsignedT
) >> 1) as Self
262 concat
!("Returns the largest value that can be represented by this integer type.
269 ", $Feature
, "assert_eq!(", stringify
!($SelfT
), "::max_value(), ", stringify
!($Max
), ");",
272 #[stable(feature = "rust1", since = "1.0.0")]
275 pub const fn max_value() -> Self {
281 concat
!("Converts a string slice in a given base to an integer.
283 The string is expected to be an optional `+` or `-` sign followed by digits.
284 Leading and trailing whitespace represent an error. Digits are a subset of these characters,
285 depending on `radix`:
293 This function panics if `radix` is not in the range from 2 to 36.
300 ", $Feature
, "assert_eq!(", stringify
!($SelfT
), "::from_str_radix(\"A\", 16), Ok(10));",
303 #[stable(feature = "rust1", since = "1.0.0")]
304 pub fn from_str_radix(src
: &str, radix
: u32) -> Result
<Self, ParseIntError
> {
305 from_str_radix(src
, radix
)
310 concat
!("Returns the number of ones in the binary representation of `self`.
317 ", $Feature
, "let n = 0b100_0000", stringify
!($SelfT
), ";
319 assert_eq!(n.count_ones(), 1);",
323 #[stable(feature = "rust1", since = "1.0.0")]
325 pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
329 concat
!("Returns the number of zeros in the binary representation of `self`.
336 ", $Feature
, "assert_eq!(", stringify
!($SelfT
), "::max_value().count_zeros(), 1);", $EndFeature
, "
338 #[stable(feature = "rust1", since = "1.0.0")]
340 pub const fn count_zeros(self) -> u32 {
346 concat
!("Returns the number of leading zeros in the binary representation of `self`.
353 ", $Feature
, "let n = -1", stringify
!($SelfT
), ";
355 assert_eq!(n.leading_zeros(), 0);",
358 #[stable(feature = "rust1", since = "1.0.0")]
360 pub const fn leading_zeros(self) -> u32 {
361 (self as $UnsignedT
).leading_zeros()
366 concat
!("Returns the number of trailing zeros in the binary representation of `self`.
373 ", $Feature
, "let n = -4", stringify
!($SelfT
), ";
375 assert_eq!(n.trailing_zeros(), 2);",
378 #[stable(feature = "rust1", since = "1.0.0")]
380 pub const fn trailing_zeros(self) -> u32 {
381 (self as $UnsignedT
).trailing_zeros()
386 concat
!("Shifts the bits to the left by a specified amount, `n`,
387 wrapping the truncated bits to the end of the resulting integer.
389 Please note this isn't the same operation as the `<<` shifting operator!
396 let n = ", $rot_op
, stringify
!($SelfT
), ";
397 let m = ", $rot_result
, ";
399 assert_eq!(n.rotate_left(", $rot
, "), m);
401 #[stable(feature = "rust1", since = "1.0.0")]
402 #[must_use = "this returns the result of the operation, \
403 without modifying the original"]
405 pub const fn rotate_left(self, n
: u32) -> Self {
406 (self as $UnsignedT
).rotate_left(n
) as Self
411 concat
!("Shifts the bits to the right by a specified amount, `n`,
412 wrapping the truncated bits to the beginning of the resulting
415 Please note this isn't the same operation as the `>>` shifting operator!
422 let n = ", $rot_result
, stringify
!($SelfT
), ";
423 let m = ", $rot_op
, ";
425 assert_eq!(n.rotate_right(", $rot
, "), m);
427 #[stable(feature = "rust1", since = "1.0.0")]
428 #[must_use = "this returns the result of the operation, \
429 without modifying the original"]
431 pub const fn rotate_right(self, n
: u32) -> Self {
432 (self as $UnsignedT
).rotate_right(n
) as Self
437 concat
!("Reverses the byte order of the integer.
444 let n = ", $swap_op
, stringify
!($SelfT
), ";
446 let m = n.swap_bytes();
448 assert_eq!(m, ", $swapped
, ");
450 #[stable(feature = "rust1", since = "1.0.0")]
452 pub const fn swap_bytes(self) -> Self {
453 (self as $UnsignedT
).swap_bytes() as Self
458 concat
!("Reverses the bit pattern of the integer.
465 #![feature(reverse_bits)]
467 let n = ", $swap_op
, stringify
!($SelfT
), ";
468 let m = n.reverse_bits();
470 assert_eq!(m, ", $reversed
, ");
472 #[unstable(feature = "reverse_bits", issue = "48763")]
473 #[rustc_const_unstable(feature = "const_int_conversion")]
475 pub const fn reverse_bits(self) -> Self {
476 (self as $UnsignedT
).reverse_bits() as Self
481 concat
!("Converts an integer from big endian to the target's endianness.
483 On big endian this is a no-op. On little endian the bytes are swapped.
490 ", $Feature
, "let n = 0x1A", stringify
!($SelfT
), ";
492 if cfg!(target_endian = \"big\") {
493 assert_eq!(", stringify
!($SelfT
), "::from_be(n), n)
495 assert_eq!(", stringify
!($SelfT
), "::from_be(n), n.swap_bytes())
499 #[stable(feature = "rust1", since = "1.0.0")]
501 pub const fn from_be(x
: Self) -> Self {
502 #[cfg(target_endian = "big")]
506 #[cfg(not(target_endian = "big"))]
514 concat
!("Converts an integer from little endian to the target's endianness.
516 On little endian this is a no-op. On big endian the bytes are swapped.
523 ", $Feature
, "let n = 0x1A", stringify
!($SelfT
), ";
525 if cfg!(target_endian = \"little\") {
526 assert_eq!(", stringify
!($SelfT
), "::from_le(n), n)
528 assert_eq!(", stringify
!($SelfT
), "::from_le(n), n.swap_bytes())
532 #[stable(feature = "rust1", since = "1.0.0")]
534 pub const fn from_le(x
: Self) -> Self {
535 #[cfg(target_endian = "little")]
539 #[cfg(not(target_endian = "little"))]
547 concat
!("Converts `self` to big endian from the target's endianness.
549 On big endian this is a no-op. On little endian the bytes are swapped.
556 ", $Feature
, "let n = 0x1A", stringify
!($SelfT
), ";
558 if cfg!(target_endian = \"big\") {
559 assert_eq!(n.to_be(), n)
561 assert_eq!(n.to_be(), n.swap_bytes())
565 #[stable(feature = "rust1", since = "1.0.0")]
567 pub const fn to_be(self) -> Self { // or not to be?
568 #[cfg(target_endian = "big")]
572 #[cfg(not(target_endian = "big"))]
580 concat
!("Converts `self` to little endian from the target's endianness.
582 On little endian this is a no-op. On big endian the bytes are swapped.
589 ", $Feature
, "let n = 0x1A", stringify
!($SelfT
), ";
591 if cfg!(target_endian = \"little\") {
592 assert_eq!(n.to_le(), n)
594 assert_eq!(n.to_le(), n.swap_bytes())
598 #[stable(feature = "rust1", since = "1.0.0")]
600 pub const fn to_le(self) -> Self {
601 #[cfg(target_endian = "little")]
605 #[cfg(not(target_endian = "little"))]
613 concat
!("Checked integer addition. Computes `self + rhs`, returning `None`
614 if overflow occurred.
621 ", $Feature
, "assert_eq!((", stringify
!($SelfT
),
622 "::max_value() - 2).checked_add(1), Some(", stringify
!($SelfT
), "::max_value() - 1));
623 assert_eq!((", stringify
!($SelfT
), "::max_value() - 2).checked_add(3), None);",
626 #[stable(feature = "rust1", since = "1.0.0")]
627 #[must_use = "this returns the result of the operation, \
628 without modifying the original"]
630 pub fn checked_add(self, rhs
: Self) -> Option
<Self> {
631 let (a
, b
) = self.overflowing_add(rhs
);
632 if b {None}
else {Some(a)}
637 concat
!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
645 ", $Feature
, "assert_eq!((", stringify
!($SelfT
),
646 "::min_value() + 2).checked_sub(1), Some(", stringify
!($SelfT
), "::min_value() + 1));
647 assert_eq!((", stringify
!($SelfT
), "::min_value() + 2).checked_sub(3), None);",
650 #[stable(feature = "rust1", since = "1.0.0")]
651 #[must_use = "this returns the result of the operation, \
652 without modifying the original"]
654 pub fn checked_sub(self, rhs
: Self) -> Option
<Self> {
655 let (a
, b
) = self.overflowing_sub(rhs
);
656 if b {None}
else {Some(a)}
661 concat
!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
669 ", $Feature
, "assert_eq!(", stringify
!($SelfT
),
670 "::max_value().checked_mul(1), Some(", stringify
!($SelfT
), "::max_value()));
671 assert_eq!(", stringify
!($SelfT
), "::max_value().checked_mul(2), None);",
674 #[stable(feature = "rust1", since = "1.0.0")]
675 #[must_use = "this returns the result of the operation, \
676 without modifying the original"]
678 pub fn checked_mul(self, rhs
: Self) -> Option
<Self> {
679 let (a
, b
) = self.overflowing_mul(rhs
);
680 if b {None}
else {Some(a)}
685 concat
!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
686 or the division results in overflow.
693 ", $Feature
, "assert_eq!((", stringify
!($SelfT
),
694 "::min_value() + 1).checked_div(-1), Some(", stringify
!($Max
), "));
695 assert_eq!(", stringify
!($SelfT
), "::min_value().checked_div(-1), None);
696 assert_eq!((1", stringify
!($SelfT
), ").checked_div(0), None);",
699 #[stable(feature = "rust1", since = "1.0.0")]
700 #[must_use = "this returns the result of the operation, \
701 without modifying the original"]
703 pub fn checked_div(self, rhs
: Self) -> Option
<Self> {
704 if rhs
== 0 || (self == Self::min_value() && rhs
== -1) {
707 Some(unsafe { intrinsics::unchecked_div(self, rhs) }
)
713 concat
!("Checked Euclidean division. Computes `self.div_euclid(rhs)`,
714 returning `None` if `rhs == 0` or the division results in overflow.
721 #![feature(euclidean_division)]
722 assert_eq!((", stringify
!($SelfT
),
723 "::min_value() + 1).checked_div_euclid(-1), Some(", stringify
!($Max
), "));
724 assert_eq!(", stringify
!($SelfT
), "::min_value().checked_div_euclid(-1), None);
725 assert_eq!((1", stringify
!($SelfT
), ").checked_div_euclid(0), None);
727 #[unstable(feature = "euclidean_division", issue = "49048")]
728 #[must_use = "this returns the result of the operation, \
729 without modifying the original"]
731 pub fn checked_div_euclid(self, rhs
: Self) -> Option
<Self> {
732 if rhs
== 0 || (self == Self::min_value() && rhs
== -1) {
735 Some(self.div_euclid(rhs
))
741 concat
!("Checked integer remainder. Computes `self % rhs`, returning `None` if
742 `rhs == 0` or the division results in overflow.
749 ", $Feature
, "use std::", stringify
!($SelfT
), ";
751 assert_eq!(5", stringify
!($SelfT
), ".checked_rem(2), Some(1));
752 assert_eq!(5", stringify
!($SelfT
), ".checked_rem(0), None);
753 assert_eq!(", stringify
!($SelfT
), "::MIN.checked_rem(-1), None);",
756 #[stable(feature = "wrapping", since = "1.7.0")]
757 #[must_use = "this returns the result of the operation, \
758 without modifying the original"]
760 pub fn checked_rem(self, rhs
: Self) -> Option
<Self> {
761 if rhs
== 0 || (self == Self::min_value() && rhs
== -1) {
764 Some(unsafe { intrinsics::unchecked_rem(self, rhs) }
)
770 concat
!("Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`
771 if `rhs == 0` or the division results in overflow.
778 #![feature(euclidean_division)]
779 use std::", stringify
!($SelfT
), ";
781 assert_eq!(5", stringify
!($SelfT
), ".checked_rem_euclid(2), Some(1));
782 assert_eq!(5", stringify
!($SelfT
), ".checked_rem_euclid(0), None);
783 assert_eq!(", stringify
!($SelfT
), "::MIN.checked_rem_euclid(-1), None);
785 #[unstable(feature = "euclidean_division", issue = "49048")]
786 #[must_use = "this returns the result of the operation, \
787 without modifying the original"]
789 pub fn checked_rem_euclid(self, rhs
: Self) -> Option
<Self> {
790 if rhs
== 0 || (self == Self::min_value() && rhs
== -1) {
793 Some(self.rem_euclid(rhs
))
799 concat
!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
806 ", $Feature
, "use std::", stringify
!($SelfT
), ";
808 assert_eq!(5", stringify
!($SelfT
), ".checked_neg(), Some(-5));
809 assert_eq!(", stringify
!($SelfT
), "::MIN.checked_neg(), None);",
812 #[stable(feature = "wrapping", since = "1.7.0")]
814 pub fn checked_neg(self) -> Option
<Self> {
815 let (a
, b
) = self.overflowing_neg();
816 if b {None}
else {Some(a)}
821 concat
!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
822 than or equal to the number of bits in `self`.
829 ", $Feature
, "assert_eq!(0x1", stringify
!($SelfT
), ".checked_shl(4), Some(0x10));
830 assert_eq!(0x1", stringify
!($SelfT
), ".checked_shl(129), None);",
833 #[stable(feature = "wrapping", since = "1.7.0")]
834 #[must_use = "this returns the result of the operation, \
835 without modifying the original"]
837 pub fn checked_shl(self, rhs
: u32) -> Option
<Self> {
838 let (a
, b
) = self.overflowing_shl(rhs
);
839 if b {None}
else {Some(a)}
844 concat
!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
845 larger than or equal to the number of bits in `self`.
852 ", $Feature
, "assert_eq!(0x10", stringify
!($SelfT
), ".checked_shr(4), Some(0x1));
853 assert_eq!(0x10", stringify
!($SelfT
), ".checked_shr(128), None);",
856 #[stable(feature = "wrapping", since = "1.7.0")]
857 #[must_use = "this returns the result of the operation, \
858 without modifying the original"]
860 pub fn checked_shr(self, rhs
: u32) -> Option
<Self> {
861 let (a
, b
) = self.overflowing_shr(rhs
);
862 if b {None}
else {Some(a)}
867 concat
!("Checked absolute value. Computes `self.abs()`, returning `None` if
875 ", $Feature
, "use std::", stringify
!($SelfT
), ";
877 assert_eq!((-5", stringify
!($SelfT
), ").checked_abs(), Some(5));
878 assert_eq!(", stringify
!($SelfT
), "::MIN.checked_abs(), None);",
881 #[stable(feature = "no_panic_abs", since = "1.13.0")]
883 pub fn checked_abs(self) -> Option
<Self> {
884 if self.is_negative() {
893 concat
!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
901 ", $Feature
, "assert_eq!(8", stringify
!($SelfT
), ".checked_pow(2), Some(64));
902 assert_eq!(", stringify
!($SelfT
), "::max_value().checked_pow(2), None);",
906 #[stable(feature = "no_panic_pow", since = "1.34.0")]
907 #[must_use = "this returns the result of the operation, \
908 without modifying the original"]
910 pub fn checked_pow(self, mut exp
: u32) -> Option
<Self> {
912 let mut acc
: Self = 1;
916 acc
= acc
.checked_mul(base
)?
;
919 base
= base
.checked_mul(base
)?
;
922 // Deal with the final bit of the exponent separately, since
923 // squaring the base afterwards is not necessary and may cause a
924 // needless overflow.
926 acc
= acc
.checked_mul(base
)?
;
934 concat
!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
935 bounds instead of overflowing.
942 ", $Feature
, "assert_eq!(100", stringify
!($SelfT
), ".saturating_add(1), 101);
943 assert_eq!(", stringify
!($SelfT
), "::max_value().saturating_add(100), ", stringify
!($SelfT
),
948 #[stable(feature = "rust1", since = "1.0.0")]
949 #[rustc_const_unstable(feature = "const_saturating_int_methods")]
950 #[must_use = "this returns the result of the operation, \
951 without modifying the original"]
953 pub const fn saturating_add(self, rhs
: Self) -> Self {
954 intrinsics
::saturating_add(self, rhs
)
960 concat
!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
961 numeric bounds instead of overflowing.
968 ", $Feature
, "assert_eq!(100", stringify
!($SelfT
), ".saturating_sub(127), -27);
969 assert_eq!(", stringify
!($SelfT
), "::min_value().saturating_sub(100), ", stringify
!($SelfT
),
973 #[stable(feature = "rust1", since = "1.0.0")]
974 #[rustc_const_unstable(feature = "const_saturating_int_methods")]
975 #[must_use = "this returns the result of the operation, \
976 without modifying the original"]
978 pub const fn saturating_sub(self, rhs
: Self) -> Self {
979 intrinsics
::saturating_sub(self, rhs
)
984 concat
!("Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
985 instead of overflowing.
992 ", $Feature
, "#![feature(saturating_neg)]
993 assert_eq!(100", stringify
!($SelfT
), ".saturating_neg(), -100);
994 assert_eq!((-100", stringify
!($SelfT
), ").saturating_neg(), 100);
995 assert_eq!(", stringify
!($SelfT
), "::min_value().saturating_neg(), ", stringify
!($SelfT
),
997 assert_eq!(", stringify
!($SelfT
), "::max_value().saturating_neg(), ", stringify
!($SelfT
),
998 "::min_value() + 1);",
1002 #[unstable(feature = "saturating_neg", issue = "59983")]
1004 pub fn saturating_neg(self) -> Self {
1005 intrinsics
::saturating_sub(0, self)
1010 concat
!("Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
1011 MIN` instead of overflowing.
1018 ", $Feature
, "#![feature(saturating_neg)]
1019 assert_eq!(100", stringify
!($SelfT
), ".saturating_abs(), 100);
1020 assert_eq!((-100", stringify
!($SelfT
), ").saturating_abs(), 100);
1021 assert_eq!(", stringify
!($SelfT
), "::min_value().saturating_abs(), ", stringify
!($SelfT
),
1023 assert_eq!((", stringify
!($SelfT
), "::min_value() + 1).saturating_abs(), ", stringify
!($SelfT
),
1028 #[unstable(feature = "saturating_neg", issue = "59983")]
1030 pub fn saturating_abs(self) -> Self {
1031 if self.is_negative() {
1032 self.saturating_neg()
1040 concat
!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
1041 numeric bounds instead of overflowing.
1048 ", $Feature
, "use std::", stringify
!($SelfT
), ";
1050 assert_eq!(10", stringify
!($SelfT
), ".saturating_mul(12), 120);
1051 assert_eq!(", stringify
!($SelfT
), "::MAX.saturating_mul(10), ", stringify
!($SelfT
), "::MAX);
1052 assert_eq!(", stringify
!($SelfT
), "::MIN.saturating_mul(10), ", stringify
!($SelfT
), "::MIN);",
1055 #[stable(feature = "wrapping", since = "1.7.0")]
1056 #[must_use = "this returns the result of the operation, \
1057 without modifying the original"]
1059 pub fn saturating_mul(self, rhs
: Self) -> Self {
1060 self.checked_mul(rhs
).unwrap_or_else(|| {
1061 if (self < 0 && rhs
< 0) || (self > 0 && rhs
> 0) {
1071 concat
!("Saturating integer exponentiation. Computes `self.pow(exp)`,
1072 saturating at the numeric bounds instead of overflowing.
1079 ", $Feature
, "use std::", stringify
!($SelfT
), ";
1081 assert_eq!((-4", stringify
!($SelfT
), ").saturating_pow(3), -64);
1082 assert_eq!(", stringify
!($SelfT
), "::MIN.saturating_pow(2), ", stringify
!($SelfT
), "::MAX);
1083 assert_eq!(", stringify
!($SelfT
), "::MIN.saturating_pow(3), ", stringify
!($SelfT
), "::MIN);",
1086 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1087 #[must_use = "this returns the result of the operation, \
1088 without modifying the original"]
1090 pub fn saturating_pow(self, exp
: u32) -> Self {
1091 match self.checked_pow(exp
) {
1093 None
if self < 0 && exp
% 2 == 1 => Self::min_value(),
1094 None
=> Self::max_value(),
1100 concat
!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
1101 boundary of the type.
1108 ", $Feature
, "assert_eq!(100", stringify
!($SelfT
), ".wrapping_add(27), 127);
1109 assert_eq!(", stringify
!($SelfT
), "::max_value().wrapping_add(2), ", stringify
!($SelfT
),
1110 "::min_value() + 1);",
1113 #[stable(feature = "rust1", since = "1.0.0")]
1114 #[must_use = "this returns the result of the operation, \
1115 without modifying the original"]
1117 pub const fn wrapping_add(self, rhs
: Self) -> Self {
1118 intrinsics
::overflowing_add(self, rhs
)
1123 concat
!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1124 boundary of the type.
1131 ", $Feature
, "assert_eq!(0", stringify
!($SelfT
), ".wrapping_sub(127), -127);
1132 assert_eq!((-2", stringify
!($SelfT
), ").wrapping_sub(", stringify
!($SelfT
), "::max_value()), ",
1133 stringify
!($SelfT
), "::max_value());",
1136 #[stable(feature = "rust1", since = "1.0.0")]
1137 #[must_use = "this returns the result of the operation, \
1138 without modifying the original"]
1140 pub const fn wrapping_sub(self, rhs
: Self) -> Self {
1141 intrinsics
::overflowing_sub(self, rhs
)
1146 concat
!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1147 the boundary of the type.
1154 ", $Feature
, "assert_eq!(10", stringify
!($SelfT
), ".wrapping_mul(12), 120);
1155 assert_eq!(11i8.wrapping_mul(12), -124);",
1158 #[stable(feature = "rust1", since = "1.0.0")]
1159 #[must_use = "this returns the result of the operation, \
1160 without modifying the original"]
1162 pub const fn wrapping_mul(self, rhs
: Self) -> Self {
1163 intrinsics
::overflowing_mul(self, rhs
)
1168 concat
!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1169 boundary of the type.
1171 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1172 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1173 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1177 This function will panic if `rhs` is 0.
1184 ", $Feature
, "assert_eq!(100", stringify
!($SelfT
), ".wrapping_div(10), 10);
1185 assert_eq!((-128i8).wrapping_div(-1), -128);",
1188 #[stable(feature = "num_wrapping", since = "1.2.0")]
1189 #[must_use = "this returns the result of the operation, \
1190 without modifying the original"]
1192 pub fn wrapping_div(self, rhs
: Self) -> Self {
1193 self.overflowing_div(rhs
).0
1198 concat
!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
1199 wrapping around at the boundary of the type.
1201 Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1202 for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1203 type. In this case, this method returns `MIN` itself.
1207 This function will panic if `rhs` is 0.
1214 #![feature(euclidean_division)]
1215 assert_eq!(100", stringify
!($SelfT
), ".wrapping_div_euclid(10), 10);
1216 assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
1218 #[unstable(feature = "euclidean_division", issue = "49048")]
1219 #[must_use = "this returns the result of the operation, \
1220 without modifying the original"]
1222 pub fn wrapping_div_euclid(self, rhs
: Self) -> Self {
1223 self.overflowing_div_euclid(rhs
).0
1228 concat
!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1229 boundary of the type.
1231 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1232 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1233 this function returns `0`.
1237 This function will panic if `rhs` is 0.
1244 ", $Feature
, "assert_eq!(100", stringify
!($SelfT
), ".wrapping_rem(10), 0);
1245 assert_eq!((-128i8).wrapping_rem(-1), 0);",
1248 #[stable(feature = "num_wrapping", since = "1.2.0")]
1249 #[must_use = "this returns the result of the operation, \
1250 without modifying the original"]
1252 pub fn wrapping_rem(self, rhs
: Self) -> Self {
1253 self.overflowing_rem(rhs
).0
1258 concat
!("Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
1259 at the boundary of the type.
1261 Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1262 for the type). In this case, this method returns 0.
1266 This function will panic if `rhs` is 0.
1273 #![feature(euclidean_division)]
1274 assert_eq!(100", stringify
!($SelfT
), ".wrapping_rem_euclid(10), 0);
1275 assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
1277 #[unstable(feature = "euclidean_division", issue = "49048")]
1278 #[must_use = "this returns the result of the operation, \
1279 without modifying the original"]
1281 pub fn wrapping_rem_euclid(self, rhs
: Self) -> Self {
1282 self.overflowing_rem_euclid(rhs
).0
1287 concat
!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1290 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1291 is the negative minimal value for the type); this is a positive value that is too large to represent
1292 in the type. In such a case, this function returns `MIN` itself.
1299 ", $Feature
, "assert_eq!(100", stringify
!($SelfT
), ".wrapping_neg(), -100);
1300 assert_eq!(", stringify
!($SelfT
), "::min_value().wrapping_neg(), ", stringify
!($SelfT
),
1304 #[stable(feature = "num_wrapping", since = "1.2.0")]
1306 pub const fn wrapping_neg(self) -> Self {
1307 self.overflowing_neg().0
1312 concat
!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1313 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1315 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1316 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1317 The primitive integer types all implement a `rotate_left` function, which may be what you want
1325 ", $Feature
, "assert_eq!((-1", stringify
!($SelfT
), ").wrapping_shl(7), -128);
1326 assert_eq!((-1", stringify
!($SelfT
), ").wrapping_shl(128), -1);",
1329 #[stable(feature = "num_wrapping", since = "1.2.0")]
1330 #[must_use = "this returns the result of the operation, \
1331 without modifying the original"]
1333 pub const fn wrapping_shl(self, rhs
: u32) -> Self {
1335 intrinsics
::unchecked_shl(self, (rhs
& ($BITS
- 1)) as $SelfT
)
1341 concat
!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1342 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1344 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1345 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1346 end. The primitive integer types all implement a `rotate_right` function, which may be what you want
1354 ", $Feature
, "assert_eq!((-128", stringify
!($SelfT
), ").wrapping_shr(7), -1);
1355 assert_eq!((-128i16).wrapping_shr(64), -128);",
1358 #[stable(feature = "num_wrapping", since = "1.2.0")]
1359 #[must_use = "this returns the result of the operation, \
1360 without modifying the original"]
1362 pub const fn wrapping_shr(self, rhs
: u32) -> Self {
1364 intrinsics
::unchecked_shr(self, (rhs
& ($BITS
- 1)) as $SelfT
)
1370 concat
!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1371 the boundary of the type.
1373 The only case where such wrapping can occur is when one takes the absolute value of the negative
1374 minimal value for the type this is a positive value that is too large to represent in the type. In
1375 such a case, this function returns `MIN` itself.
1382 ", $Feature
, "assert_eq!(100", stringify
!($SelfT
), ".wrapping_abs(), 100);
1383 assert_eq!((-100", stringify
!($SelfT
), ").wrapping_abs(), 100);
1384 assert_eq!(", stringify
!($SelfT
), "::min_value().wrapping_abs(), ", stringify
!($SelfT
),
1386 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1389 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1391 pub fn wrapping_abs(self) -> Self {
1392 if self.is_negative() {
1401 concat
!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1402 wrapping around at the boundary of the type.
1409 ", $Feature
, "assert_eq!(3", stringify
!($SelfT
), ".wrapping_pow(4), 81);
1410 assert_eq!(3i8.wrapping_pow(5), -13);
1411 assert_eq!(3i8.wrapping_pow(6), -39);",
1414 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1415 #[must_use = "this returns the result of the operation, \
1416 without modifying the original"]
1418 pub fn wrapping_pow(self, mut exp
: u32) -> Self {
1419 let mut base
= self;
1420 let mut acc
: Self = 1;
1424 acc
= acc
.wrapping_mul(base
);
1427 base
= base
.wrapping_mul(base
);
1430 // Deal with the final bit of the exponent separately, since
1431 // squaring the base afterwards is not necessary and may cause a
1432 // needless overflow.
1434 acc
= acc
.wrapping_mul(base
);
1442 concat
!("Calculates `self` + `rhs`
1444 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1445 occur. If an overflow would have occurred then the wrapped value is returned.
1452 ", $Feature
, "use std::", stringify
!($SelfT
), ";
1454 assert_eq!(5", stringify
!($SelfT
), ".overflowing_add(2), (7, false));
1455 assert_eq!(", stringify
!($SelfT
), "::MAX.overflowing_add(1), (", stringify
!($SelfT
),
1456 "::MIN, true));", $EndFeature
, "
1458 #[stable(feature = "wrapping", since = "1.7.0")]
1459 #[must_use = "this returns the result of the operation, \
1460 without modifying the original"]
1462 pub const fn overflowing_add(self, rhs
: Self) -> (Self, bool
) {
1463 let (a
, b
) = intrinsics
::add_with_overflow(self as $ActualT
, rhs
as $ActualT
);
1469 concat
!("Calculates `self` - `rhs`
1471 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1472 would occur. If an overflow would have occurred then the wrapped value is returned.
1479 ", $Feature
, "use std::", stringify
!($SelfT
), ";
1481 assert_eq!(5", stringify
!($SelfT
), ".overflowing_sub(2), (3, false));
1482 assert_eq!(", stringify
!($SelfT
), "::MIN.overflowing_sub(1), (", stringify
!($SelfT
),
1483 "::MAX, true));", $EndFeature
, "
1485 #[stable(feature = "wrapping", since = "1.7.0")]
1486 #[must_use = "this returns the result of the operation, \
1487 without modifying the original"]
1489 pub const fn overflowing_sub(self, rhs
: Self) -> (Self, bool
) {
1490 let (a
, b
) = intrinsics
::sub_with_overflow(self as $ActualT
, rhs
as $ActualT
);
1496 concat
!("Calculates the multiplication of `self` and `rhs`.
1498 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1499 would occur. If an overflow would have occurred then the wrapped value is returned.
1506 ", $Feature
, "assert_eq!(5", stringify
!($SelfT
), ".overflowing_mul(2), (10, false));
1507 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1510 #[stable(feature = "wrapping", since = "1.7.0")]
1511 #[must_use = "this returns the result of the operation, \
1512 without modifying the original"]
1514 pub const fn overflowing_mul(self, rhs
: Self) -> (Self, bool
) {
1515 let (a
, b
) = intrinsics
::mul_with_overflow(self as $ActualT
, rhs
as $ActualT
);
1521 concat
!("Calculates the divisor when `self` is divided by `rhs`.
1523 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1524 occur. If an overflow would occur then self is returned.
1528 This function will panic if `rhs` is 0.
1535 ", $Feature
, "use std::", stringify
!($SelfT
), ";
1537 assert_eq!(5", stringify
!($SelfT
), ".overflowing_div(2), (2, false));
1538 assert_eq!(", stringify
!($SelfT
), "::MIN.overflowing_div(-1), (", stringify
!($SelfT
),
1543 #[stable(feature = "wrapping", since = "1.7.0")]
1544 #[must_use = "this returns the result of the operation, \
1545 without modifying the original"]
1546 pub fn overflowing_div(self, rhs
: Self) -> (Self, bool
) {
1547 if self == Self::min_value() && rhs
== -1 {
1556 concat
!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1558 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1559 occur. If an overflow would occur then `self` is returned.
1563 This function will panic if `rhs` is 0.
1570 #![feature(euclidean_division)]
1571 use std::", stringify
!($SelfT
), ";
1573 assert_eq!(5", stringify
!($SelfT
), ".overflowing_div_euclid(2), (2, false));
1574 assert_eq!(", stringify
!($SelfT
), "::MIN.overflowing_div_euclid(-1), (", stringify
!($SelfT
),
1578 #[unstable(feature = "euclidean_division", issue = "49048")]
1579 #[must_use = "this returns the result of the operation, \
1580 without modifying the original"]
1581 pub fn overflowing_div_euclid(self, rhs
: Self) -> (Self, bool
) {
1582 if self == Self::min_value() && rhs
== -1 {
1585 (self.div_euclid(rhs
), false)
1591 concat
!("Calculates the remainder when `self` is divided by `rhs`.
1593 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1594 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1598 This function will panic if `rhs` is 0.
1605 ", $Feature
, "use std::", stringify
!($SelfT
), ";
1607 assert_eq!(5", stringify
!($SelfT
), ".overflowing_rem(2), (1, false));
1608 assert_eq!(", stringify
!($SelfT
), "::MIN.overflowing_rem(-1), (0, true));",
1612 #[stable(feature = "wrapping", since = "1.7.0")]
1613 #[must_use = "this returns the result of the operation, \
1614 without modifying the original"]
1615 pub fn overflowing_rem(self, rhs
: Self) -> (Self, bool
) {
1616 if self == Self::min_value() && rhs
== -1 {
1626 concat
!("Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
1628 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1629 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1633 This function will panic if `rhs` is 0.
1640 #![feature(euclidean_division)]
1641 use std::", stringify
!($SelfT
), ";
1643 assert_eq!(5", stringify
!($SelfT
), ".overflowing_rem_euclid(2), (1, false));
1644 assert_eq!(", stringify
!($SelfT
), "::MIN.overflowing_rem_euclid(-1), (0, true));
1646 #[unstable(feature = "euclidean_division", issue = "49048")]
1647 #[must_use = "this returns the result of the operation, \
1648 without modifying the original"]
1650 pub fn overflowing_rem_euclid(self, rhs
: Self) -> (Self, bool
) {
1651 if self == Self::min_value() && rhs
== -1 {
1654 (self.rem_euclid(rhs
), false)
1661 concat
!("Negates self, overflowing if this is equal to the minimum value.
1663 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1664 happened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the
1665 minimum value will be returned again and `true` will be returned for an overflow happening.
1672 ", $Feature
, "use std::", stringify
!($SelfT
), ";
1674 assert_eq!(2", stringify
!($SelfT
), ".overflowing_neg(), (-2, false));
1675 assert_eq!(", stringify
!($SelfT
), "::MIN.overflowing_neg(), (", stringify
!($SelfT
),
1676 "::MIN, true));", $EndFeature
, "
1679 #[stable(feature = "wrapping", since = "1.7.0")]
1680 pub const fn overflowing_neg(self) -> (Self, bool
) {
1681 ((!self).wrapping_add(1), self == Self::min_value())
1686 concat
!("Shifts self left by `rhs` bits.
1688 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1689 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1690 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1697 ", $Feature
, "assert_eq!(0x1", stringify
!($SelfT
),".overflowing_shl(4), (0x10, false));
1698 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1701 #[stable(feature = "wrapping", since = "1.7.0")]
1702 #[must_use = "this returns the result of the operation, \
1703 without modifying the original"]
1705 pub const fn overflowing_shl(self, rhs
: u32) -> (Self, bool
) {
1706 (self.wrapping_shl(rhs
), (rhs
> ($BITS
- 1)))
1711 concat
!("Shifts self right by `rhs` bits.
1713 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1714 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1715 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1722 ", $Feature
, "assert_eq!(0x10", stringify
!($SelfT
), ".overflowing_shr(4), (0x1, false));
1723 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1726 #[stable(feature = "wrapping", since = "1.7.0")]
1727 #[must_use = "this returns the result of the operation, \
1728 without modifying the original"]
1730 pub const fn overflowing_shr(self, rhs
: u32) -> (Self, bool
) {
1731 (self.wrapping_shr(rhs
), (rhs
> ($BITS
- 1)))
1736 concat
!("Computes the absolute value of `self`.
1738 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1739 happened. If self is the minimum value (e.g., ", stringify
!($SelfT
), "::MIN for values of type
1740 ", stringify
!($SelfT
), "), then the minimum value will be returned again and true will be returned
1741 for an overflow happening.
1748 ", $Feature
, "assert_eq!(10", stringify
!($SelfT
), ".overflowing_abs(), (10, false));
1749 assert_eq!((-10", stringify
!($SelfT
), ").overflowing_abs(), (10, false));
1750 assert_eq!((", stringify
!($SelfT
), "::min_value()).overflowing_abs(), (", stringify
!($SelfT
),
1751 "::min_value(), true));",
1754 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1756 pub fn overflowing_abs(self) -> (Self, bool
) {
1757 if self.is_negative() {
1758 self.overflowing_neg()
1766 concat
!("Raises self to the power of `exp`, using exponentiation by squaring.
1768 Returns a tuple of the exponentiation along with a bool indicating
1769 whether an overflow happened.
1776 ", $Feature
, "assert_eq!(3", stringify
!($SelfT
), ".overflowing_pow(4), (81, false));
1777 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
1780 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1781 #[must_use = "this returns the result of the operation, \
1782 without modifying the original"]
1784 pub fn overflowing_pow(self, mut exp
: u32) -> (Self, bool
) {
1785 let mut base
= self;
1786 let mut acc
: Self = 1;
1787 let mut overflown
= false;
1788 // Scratch space for storing results of overflowing_mul.
1793 r
= acc
.overflowing_mul(base
);
1798 r
= base
.overflowing_mul(base
);
1803 // Deal with the final bit of the exponent separately, since
1804 // squaring the base afterwards is not necessary and may cause a
1805 // needless overflow.
1807 r
= acc
.overflowing_mul(base
);
1817 concat
!("Raises self to the power of `exp`, using exponentiation by squaring.
1824 ", $Feature
, "let x: ", stringify
!($SelfT
), " = 2; // or any other integer type
1826 assert_eq!(x.pow(5), 32);",
1829 #[stable(feature = "rust1", since = "1.0.0")]
1830 #[must_use = "this returns the result of the operation, \
1831 without modifying the original"]
1833 #[rustc_inherit_overflow_checks]
1834 pub fn pow(self, mut exp
: u32) -> Self {
1835 let mut base
= self;
1846 // Deal with the final bit of the exponent separately, since
1847 // squaring the base afterwards is not necessary and may cause a
1848 // needless overflow.
1858 concat
!("Calculates the quotient of Euclidean division of `self` by `rhs`.
1860 This computes the integer `n` such that `self = n * rhs + self.rem_euclid(rhs)`,
1861 with `0 <= self.rem_euclid(rhs) < rhs`.
1863 In other words, the result is `self / rhs` rounded to the integer `n`
1864 such that `self >= n * rhs`.
1865 If `self > 0`, this is equal to round towards zero (the default in Rust);
1866 if `self < 0`, this is equal to round towards +/- infinity.
1870 This function will panic if `rhs` is 0.
1877 #![feature(euclidean_division)]
1878 let a: ", stringify
!($SelfT
), " = 7; // or any other integer type
1881 assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
1882 assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
1883 assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
1884 assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
1886 #[unstable(feature = "euclidean_division", issue = "49048")]
1887 #[must_use = "this returns the result of the operation, \
1888 without modifying the original"]
1890 #[rustc_inherit_overflow_checks]
1891 pub fn div_euclid(self, rhs
: Self) -> Self {
1894 return if rhs
> 0 { q - 1 }
else { q + 1 }
1902 concat
!("Calculates the least nonnegative remainder of `self (mod rhs)`.
1904 This is done as if by the Euclidean division algorithm -- given
1905 `r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) + r`, and
1906 `0 <= r < abs(rhs)`.
1910 This function will panic if `rhs` is 0.
1917 #![feature(euclidean_division)]
1918 let a: ", stringify
!($SelfT
), " = 7; // or any other integer type
1921 assert_eq!(a.rem_euclid(b), 3);
1922 assert_eq!((-a).rem_euclid(b), 1);
1923 assert_eq!(a.rem_euclid(-b), 3);
1924 assert_eq!((-a).rem_euclid(-b), 1);
1926 #[unstable(feature = "euclidean_division", issue = "49048")]
1927 #[must_use = "this returns the result of the operation, \
1928 without modifying the original"]
1930 #[rustc_inherit_overflow_checks]
1931 pub fn rem_euclid(self, rhs
: Self) -> Self {
1946 concat
!("Computes the absolute value of `self`.
1950 The absolute value of `", stringify
!($SelfT
), "::min_value()` cannot be represented as an
1951 `", stringify
!($SelfT
), "`, and attempting to calculate it will cause an overflow. This means that
1952 code in debug mode will trigger a panic on this case and optimized code will return `",
1953 stringify
!($SelfT
), "::min_value()` without a panic.
1960 ", $Feature
, "assert_eq!(10", stringify
!($SelfT
), ".abs(), 10);
1961 assert_eq!((-10", stringify
!($SelfT
), ").abs(), 10);",
1964 #[stable(feature = "rust1", since = "1.0.0")]
1966 #[rustc_inherit_overflow_checks]
1967 pub fn abs(self) -> Self {
1968 if self.is_negative() {
1969 // Note that the #[inline] above means that the overflow
1970 // semantics of this negation depend on the crate we're being
1980 concat
!("Returns a number representing sign of `self`.
1982 - `0` if the number is zero
1983 - `1` if the number is positive
1984 - `-1` if the number is negative
1991 ", $Feature
, "assert_eq!(10", stringify
!($SelfT
), ".signum(), 1);
1992 assert_eq!(0", stringify
!($SelfT
), ".signum(), 0);
1993 assert_eq!((-10", stringify
!($SelfT
), ").signum(), -1);",
1996 #[stable(feature = "rust1", since = "1.0.0")]
1998 pub fn signum(self) -> Self {
2008 concat
!("Returns `true` if `self` is positive and `false` if the number is zero or
2016 ", $Feature
, "assert!(10", stringify
!($SelfT
), ".is_positive());
2017 assert!(!(-10", stringify
!($SelfT
), ").is_positive());",
2020 #[stable(feature = "rust1", since = "1.0.0")]
2022 pub const fn is_positive(self) -> bool { self > 0 }
2026 concat
!("Returns `true` if `self` is negative and `false` if the number is zero or
2034 ", $Feature
, "assert!((-10", stringify
!($SelfT
), ").is_negative());
2035 assert!(!10", stringify
!($SelfT
), ".is_negative());",
2038 #[stable(feature = "rust1", since = "1.0.0")]
2040 pub const fn is_negative(self) -> bool { self < 0 }
2044 concat
!("Return the memory representation of this integer as a byte array in
2045 big-endian (network) byte order.
2052 let bytes = ", $swap_op
, stringify
!($SelfT
), ".to_be_bytes();
2053 assert_eq!(bytes, ", $be_bytes
, ");
2055 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2056 #[rustc_const_unstable(feature = "const_int_conversion")]
2058 pub const fn to_be_bytes(self) -> [u8; mem
::size_of
::<Self>()] {
2059 self.to_be().to_ne_bytes()
2064 concat
!("Return the memory representation of this integer as a byte array in
2065 little-endian byte order.
2072 let bytes = ", $swap_op
, stringify
!($SelfT
), ".to_le_bytes();
2073 assert_eq!(bytes, ", $le_bytes
, ");
2075 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2076 #[rustc_const_unstable(feature = "const_int_conversion")]
2078 pub const fn to_le_bytes(self) -> [u8; mem
::size_of
::<Self>()] {
2079 self.to_le().to_ne_bytes()
2085 Return the memory representation of this integer as a byte array in
2088 As the target platform's native endianness is used, portable code
2089 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2094 [`to_be_bytes`]: #method.to_be_bytes
2095 [`to_le_bytes`]: #method.to_le_bytes
2100 let bytes = ", $swap_op
, stringify
!($SelfT
), ".to_ne_bytes();
2101 assert_eq!(bytes, if cfg!(target_endian = \"big\") {
2107 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2108 #[rustc_const_unstable(feature = "const_int_conversion")]
2110 pub const fn to_ne_bytes(self) -> [u8; mem
::size_of
::<Self>()] {
2111 unsafe { mem::transmute(self) }
2116 concat
!("Create an integer value from its representation as a byte array in
2124 let value = ", stringify
!($SelfT
), "::from_be_bytes(", $be_bytes
, ");
2125 assert_eq!(value, ", $swap_op
, ");
2128 When starting from a slice rather than an array, fallible conversion APIs can be used:
2131 use std::convert::TryInto;
2133 fn read_be_", stringify
!($SelfT
), "(input: &mut &[u8]) -> ", stringify
!($SelfT
), " {
2134 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify
!($SelfT
), ">());
2136 ", stringify
!($SelfT
), "::from_be_bytes(int_bytes.try_into().unwrap())
2139 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2140 #[rustc_const_unstable(feature = "const_int_conversion")]
2142 pub const fn from_be_bytes(bytes
: [u8; mem
::size_of
::<Self>()]) -> Self {
2143 Self::from_be(Self::from_ne_bytes(bytes
))
2149 Create an integer value from its representation as a byte array in
2157 let value = ", stringify
!($SelfT
), "::from_le_bytes(", $le_bytes
, ");
2158 assert_eq!(value, ", $swap_op
, ");
2161 When starting from a slice rather than an array, fallible conversion APIs can be used:
2164 use std::convert::TryInto;
2166 fn read_le_", stringify
!($SelfT
), "(input: &mut &[u8]) -> ", stringify
!($SelfT
), " {
2167 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify
!($SelfT
), ">());
2169 ", stringify
!($SelfT
), "::from_le_bytes(int_bytes.try_into().unwrap())
2172 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2173 #[rustc_const_unstable(feature = "const_int_conversion")]
2175 pub const fn from_le_bytes(bytes
: [u8; mem
::size_of
::<Self>()]) -> Self {
2176 Self::from_le(Self::from_ne_bytes(bytes
))
2181 concat
!("Create an integer value from its memory representation as a byte
2182 array in native endianness.
2184 As the target platform's native endianness is used, portable code
2185 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2186 appropriate instead.
2188 [`from_be_bytes`]: #method.from_be_bytes
2189 [`from_le_bytes`]: #method.from_le_bytes
2196 let value = ", stringify
!($SelfT
), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
2201 assert_eq!(value, ", $swap_op
, ");
2204 When starting from a slice rather than an array, fallible conversion APIs can be used:
2207 use std::convert::TryInto;
2209 fn read_ne_", stringify
!($SelfT
), "(input: &mut &[u8]) -> ", stringify
!($SelfT
), " {
2210 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify
!($SelfT
), ">());
2212 ", stringify
!($SelfT
), "::from_ne_bytes(int_bytes.try_into().unwrap())
2215 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2216 #[rustc_const_unstable(feature = "const_int_conversion")]
2218 pub const fn from_ne_bytes(bytes
: [u8; mem
::size_of
::<Self>()]) -> Self {
2219 unsafe { mem::transmute(bytes) }
2227 int_impl
! { i8, i8, u8, 8, -128, 127, "", "", 2, "-0x7e", "0xa", "0x12", "0x12", "0x48",
2228 "[0x12]", "[0x12]", "", "" }
2233 int_impl
! { i16, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234", "0x3412",
2234 "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
2239 int_impl
! { i32, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2240 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2241 "[0x12, 0x34, 0x56, 0x78]", "", "" }
2246 int_impl
! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "", 12,
2247 "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2248 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2249 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]", "", "" }
2254 int_impl
! { i128
, i128
, u128
, 128, -170141183460469231731687303715884105728,
2255 170141183460469231731687303715884105727, "", "", 16,
2256 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
2257 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
2258 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
2259 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2260 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
2261 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]", "", "" }
2264 #[cfg(target_pointer_width = "16")]
2267 int_impl
! { isize, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234",
2268 "0x3412", "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]",
2269 usize_isize_to_xe_bytes_doc
!(), usize_isize_from_xe_bytes_doc
!() }
2272 #[cfg(target_pointer_width = "32")]
2275 int_impl
! { isize, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2276 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2277 "[0x12, 0x34, 0x56, 0x78]",
2278 usize_isize_to_xe_bytes_doc
!(), usize_isize_from_xe_bytes_doc
!() }
2281 #[cfg(target_pointer_width = "64")]
2284 int_impl
! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "",
2285 12, "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2286 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2287 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
2288 usize_isize_to_xe_bytes_doc
!(), usize_isize_from_xe_bytes_doc
!() }
2291 // `Int` + `UnsignedInt` implemented for unsigned integers
2292 macro_rules
! uint_impl
{
2293 ($SelfT
:ty
, $ActualT
:ty
, $BITS
:expr
, $MaxV
:expr
, $Feature
:expr
, $EndFeature
:expr
,
2294 $rot
:expr
, $rot_op
:expr
, $rot_result
:expr
, $swap_op
:expr
, $swapped
:expr
,
2295 $reversed
:expr
, $le_bytes
:expr
, $be_bytes
:expr
,
2296 $to_xe_bytes_doc
:expr
, $from_xe_bytes_doc
:expr
) => {
2298 concat
!("Returns the smallest value that can be represented by this integer type.
2305 ", $Feature
, "assert_eq!(", stringify
!($SelfT
), "::min_value(), 0);", $EndFeature
, "
2307 #[stable(feature = "rust1", since = "1.0.0")]
2310 pub const fn min_value() -> Self { 0 }
2314 concat
!("Returns the largest value that can be represented by this integer type.
2321 ", $Feature
, "assert_eq!(", stringify
!($SelfT
), "::max_value(), ",
2322 stringify
!($MaxV
), ");", $EndFeature
, "
2324 #[stable(feature = "rust1", since = "1.0.0")]
2327 pub const fn max_value() -> Self { !0 }
2331 concat
!("Converts a string slice in a given base to an integer.
2333 The string is expected to be an optional `+` sign
2335 Leading and trailing whitespace represent an error.
2336 Digits are a subset of these characters, depending on `radix`:
2344 This function panics if `radix` is not in the range from 2 to 36.
2351 ", $Feature
, "assert_eq!(", stringify
!($SelfT
), "::from_str_radix(\"A\", 16), Ok(10));",
2354 #[stable(feature = "rust1", since = "1.0.0")]
2355 pub fn from_str_radix(src
: &str, radix
: u32) -> Result
<Self, ParseIntError
> {
2356 from_str_radix(src
, radix
)
2361 concat
!("Returns the number of ones in the binary representation of `self`.
2368 ", $Feature
, "let n = 0b01001100", stringify
!($SelfT
), ";
2370 assert_eq!(n.count_ones(), 3);", $EndFeature
, "
2372 #[stable(feature = "rust1", since = "1.0.0")]
2374 pub const fn count_ones(self) -> u32 {
2375 intrinsics
::ctpop(self as $ActualT
) as u32
2380 concat
!("Returns the number of zeros in the binary representation of `self`.
2387 ", $Feature
, "assert_eq!(", stringify
!($SelfT
), "::max_value().count_zeros(), 0);", $EndFeature
, "
2389 #[stable(feature = "rust1", since = "1.0.0")]
2391 pub const fn count_zeros(self) -> u32 {
2392 (!self).count_ones()
2397 concat
!("Returns the number of leading zeros in the binary representation of `self`.
2404 ", $Feature
, "let n = ", stringify
!($SelfT
), "::max_value() >> 2;
2406 assert_eq!(n.leading_zeros(), 2);", $EndFeature
, "
2408 #[stable(feature = "rust1", since = "1.0.0")]
2410 pub const fn leading_zeros(self) -> u32 {
2411 intrinsics
::ctlz(self as $ActualT
) as u32
2416 concat
!("Returns the number of trailing zeros in the binary representation
2424 ", $Feature
, "let n = 0b0101000", stringify
!($SelfT
), ";
2426 assert_eq!(n.trailing_zeros(), 3);", $EndFeature
, "
2428 #[stable(feature = "rust1", since = "1.0.0")]
2430 pub const fn trailing_zeros(self) -> u32 {
2431 intrinsics
::cttz(self) as u32
2436 concat
!("Shifts the bits to the left by a specified amount, `n`,
2437 wrapping the truncated bits to the end of the resulting integer.
2439 Please note this isn't the same operation as the `<<` shifting operator!
2446 let n = ", $rot_op
, stringify
!($SelfT
), ";
2447 let m = ", $rot_result
, ";
2449 assert_eq!(n.rotate_left(", $rot
, "), m);
2451 #[stable(feature = "rust1", since = "1.0.0")]
2452 #[must_use = "this returns the result of the operation, \
2453 without modifying the original"]
2455 pub const fn rotate_left(self, n
: u32) -> Self {
2456 intrinsics
::rotate_left(self, n
as $SelfT
)
2461 concat
!("Shifts the bits to the right by a specified amount, `n`,
2462 wrapping the truncated bits to the beginning of the resulting
2465 Please note this isn't the same operation as the `>>` shifting operator!
2472 let n = ", $rot_result
, stringify
!($SelfT
), ";
2473 let m = ", $rot_op
, ";
2475 assert_eq!(n.rotate_right(", $rot
, "), m);
2477 #[stable(feature = "rust1", since = "1.0.0")]
2478 #[must_use = "this returns the result of the operation, \
2479 without modifying the original"]
2481 pub const fn rotate_right(self, n
: u32) -> Self {
2482 intrinsics
::rotate_right(self, n
as $SelfT
)
2488 Reverses the byte order of the integer.
2495 let n = ", $swap_op
, stringify
!($SelfT
), ";
2496 let m = n.swap_bytes();
2498 assert_eq!(m, ", $swapped
, ");
2500 #[stable(feature = "rust1", since = "1.0.0")]
2502 pub const fn swap_bytes(self) -> Self {
2503 intrinsics
::bswap(self as $ActualT
) as Self
2508 concat
!("Reverses the bit pattern of the integer.
2515 #![feature(reverse_bits)]
2517 let n = ", $swap_op
, stringify
!($SelfT
), ";
2518 let m = n.reverse_bits();
2520 assert_eq!(m, ", $reversed
, ");
2522 #[unstable(feature = "reverse_bits", issue = "48763")]
2524 pub const fn reverse_bits(self) -> Self {
2525 intrinsics
::bitreverse(self as $ActualT
) as Self
2530 concat
!("Converts an integer from big endian to the target's endianness.
2532 On big endian this is a no-op. On little endian the bytes are
2540 ", $Feature
, "let n = 0x1A", stringify
!($SelfT
), ";
2542 if cfg!(target_endian = \"big\") {
2543 assert_eq!(", stringify
!($SelfT
), "::from_be(n), n)
2545 assert_eq!(", stringify
!($SelfT
), "::from_be(n), n.swap_bytes())
2548 #[stable(feature = "rust1", since = "1.0.0")]
2550 pub const fn from_be(x
: Self) -> Self {
2551 #[cfg(target_endian = "big")]
2555 #[cfg(not(target_endian = "big"))]
2563 concat
!("Converts an integer from little endian to the target's endianness.
2565 On little endian this is a no-op. On big endian the bytes are
2573 ", $Feature
, "let n = 0x1A", stringify
!($SelfT
), ";
2575 if cfg!(target_endian = \"little\") {
2576 assert_eq!(", stringify
!($SelfT
), "::from_le(n), n)
2578 assert_eq!(", stringify
!($SelfT
), "::from_le(n), n.swap_bytes())
2581 #[stable(feature = "rust1", since = "1.0.0")]
2583 pub const fn from_le(x
: Self) -> Self {
2584 #[cfg(target_endian = "little")]
2588 #[cfg(not(target_endian = "little"))]
2596 concat
!("Converts `self` to big endian from the target's endianness.
2598 On big endian this is a no-op. On little endian the bytes are
2606 ", $Feature
, "let n = 0x1A", stringify
!($SelfT
), ";
2608 if cfg!(target_endian = \"big\") {
2609 assert_eq!(n.to_be(), n)
2611 assert_eq!(n.to_be(), n.swap_bytes())
2614 #[stable(feature = "rust1", since = "1.0.0")]
2616 pub const fn to_be(self) -> Self { // or not to be?
2617 #[cfg(target_endian = "big")]
2621 #[cfg(not(target_endian = "big"))]
2629 concat
!("Converts `self` to little endian from the target's endianness.
2631 On little endian this is a no-op. On big endian the bytes are
2639 ", $Feature
, "let n = 0x1A", stringify
!($SelfT
), ";
2641 if cfg!(target_endian = \"little\") {
2642 assert_eq!(n.to_le(), n)
2644 assert_eq!(n.to_le(), n.swap_bytes())
2647 #[stable(feature = "rust1", since = "1.0.0")]
2649 pub const fn to_le(self) -> Self {
2650 #[cfg(target_endian = "little")]
2654 #[cfg(not(target_endian = "little"))]
2662 concat
!("Checked integer addition. Computes `self + rhs`, returning `None`
2663 if overflow occurred.
2670 ", $Feature
, "assert_eq!((", stringify
!($SelfT
), "::max_value() - 2).checked_add(1), ",
2671 "Some(", stringify
!($SelfT
), "::max_value() - 1));
2672 assert_eq!((", stringify
!($SelfT
), "::max_value() - 2).checked_add(3), None);", $EndFeature
, "
2674 #[stable(feature = "rust1", since = "1.0.0")]
2675 #[must_use = "this returns the result of the operation, \
2676 without modifying the original"]
2678 pub fn checked_add(self, rhs
: Self) -> Option
<Self> {
2679 let (a
, b
) = self.overflowing_add(rhs
);
2680 if b {None}
else {Some(a)}
2685 concat
!("Checked integer subtraction. Computes `self - rhs`, returning
2686 `None` if overflow occurred.
2693 ", $Feature
, "assert_eq!(1", stringify
!($SelfT
), ".checked_sub(1), Some(0));
2694 assert_eq!(0", stringify
!($SelfT
), ".checked_sub(1), None);", $EndFeature
, "
2696 #[stable(feature = "rust1", since = "1.0.0")]
2697 #[must_use = "this returns the result of the operation, \
2698 without modifying the original"]
2700 pub fn checked_sub(self, rhs
: Self) -> Option
<Self> {
2701 let (a
, b
) = self.overflowing_sub(rhs
);
2702 if b {None}
else {Some(a)}
2707 concat
!("Checked integer multiplication. Computes `self * rhs`, returning
2708 `None` if overflow occurred.
2715 ", $Feature
, "assert_eq!(5", stringify
!($SelfT
), ".checked_mul(1), Some(5));
2716 assert_eq!(", stringify
!($SelfT
), "::max_value().checked_mul(2), None);", $EndFeature
, "
2718 #[stable(feature = "rust1", since = "1.0.0")]
2719 #[must_use = "this returns the result of the operation, \
2720 without modifying the original"]
2722 pub fn checked_mul(self, rhs
: Self) -> Option
<Self> {
2723 let (a
, b
) = self.overflowing_mul(rhs
);
2724 if b {None}
else {Some(a)}
2729 concat
!("Checked integer division. Computes `self / rhs`, returning `None`
2737 ", $Feature
, "assert_eq!(128", stringify
!($SelfT
), ".checked_div(2), Some(64));
2738 assert_eq!(1", stringify
!($SelfT
), ".checked_div(0), None);", $EndFeature
, "
2740 #[stable(feature = "rust1", since = "1.0.0")]
2741 #[must_use = "this returns the result of the operation, \
2742 without modifying the original"]
2744 pub fn checked_div(self, rhs
: Self) -> Option
<Self> {
2747 rhs
=> Some(unsafe { intrinsics::unchecked_div(self, rhs) }
),
2753 concat
!("Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
2761 #![feature(euclidean_division)]
2762 assert_eq!(128", stringify
!($SelfT
), ".checked_div_euclid(2), Some(64));
2763 assert_eq!(1", stringify
!($SelfT
), ".checked_div_euclid(0), None);
2765 #[unstable(feature = "euclidean_division", issue = "49048")]
2766 #[must_use = "this returns the result of the operation, \
2767 without modifying the original"]
2769 pub fn checked_div_euclid(self, rhs
: Self) -> Option
<Self> {
2773 Some(self.div_euclid(rhs
))
2780 concat
!("Checked integer remainder. Computes `self % rhs`, returning `None`
2788 ", $Feature
, "assert_eq!(5", stringify
!($SelfT
), ".checked_rem(2), Some(1));
2789 assert_eq!(5", stringify
!($SelfT
), ".checked_rem(0), None);", $EndFeature
, "
2791 #[stable(feature = "wrapping", since = "1.7.0")]
2792 #[must_use = "this returns the result of the operation, \
2793 without modifying the original"]
2795 pub fn checked_rem(self, rhs
: Self) -> Option
<Self> {
2799 Some(unsafe { intrinsics::unchecked_rem(self, rhs) }
)
2805 concat
!("Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
2813 #![feature(euclidean_division)]
2814 assert_eq!(5", stringify
!($SelfT
), ".checked_rem_euclid(2), Some(1));
2815 assert_eq!(5", stringify
!($SelfT
), ".checked_rem_euclid(0), None);
2817 #[unstable(feature = "euclidean_division", issue = "49048")]
2818 #[must_use = "this returns the result of the operation, \
2819 without modifying the original"]
2821 pub fn checked_rem_euclid(self, rhs
: Self) -> Option
<Self> {
2825 Some(self.rem_euclid(rhs
))
2831 concat
!("Checked negation. Computes `-self`, returning `None` unless `self ==
2834 Note that negating any positive integer will overflow.
2841 ", $Feature
, "assert_eq!(0", stringify
!($SelfT
), ".checked_neg(), Some(0));
2842 assert_eq!(1", stringify
!($SelfT
), ".checked_neg(), None);", $EndFeature
, "
2844 #[stable(feature = "wrapping", since = "1.7.0")]
2846 pub fn checked_neg(self) -> Option
<Self> {
2847 let (a
, b
) = self.overflowing_neg();
2848 if b {None}
else {Some(a)}
2853 concat
!("Checked shift left. Computes `self << rhs`, returning `None`
2854 if `rhs` is larger than or equal to the number of bits in `self`.
2861 ", $Feature
, "assert_eq!(0x1", stringify
!($SelfT
), ".checked_shl(4), Some(0x10));
2862 assert_eq!(0x10", stringify
!($SelfT
), ".checked_shl(129), None);", $EndFeature
, "
2864 #[stable(feature = "wrapping", since = "1.7.0")]
2865 #[must_use = "this returns the result of the operation, \
2866 without modifying the original"]
2868 pub fn checked_shl(self, rhs
: u32) -> Option
<Self> {
2869 let (a
, b
) = self.overflowing_shl(rhs
);
2870 if b {None}
else {Some(a)}
2875 concat
!("Checked shift right. Computes `self >> rhs`, returning `None`
2876 if `rhs` is larger than or equal to the number of bits in `self`.
2883 ", $Feature
, "assert_eq!(0x10", stringify
!($SelfT
), ".checked_shr(4), Some(0x1));
2884 assert_eq!(0x10", stringify
!($SelfT
), ".checked_shr(129), None);", $EndFeature
, "
2886 #[stable(feature = "wrapping", since = "1.7.0")]
2887 #[must_use = "this returns the result of the operation, \
2888 without modifying the original"]
2890 pub fn checked_shr(self, rhs
: u32) -> Option
<Self> {
2891 let (a
, b
) = self.overflowing_shr(rhs
);
2892 if b {None}
else {Some(a)}
2897 concat
!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
2905 ", $Feature
, "assert_eq!(2", stringify
!($SelfT
), ".checked_pow(5), Some(32));
2906 assert_eq!(", stringify
!($SelfT
), "::max_value().checked_pow(2), None);", $EndFeature
, "
2908 #[stable(feature = "no_panic_pow", since = "1.34.0")]
2909 #[must_use = "this returns the result of the operation, \
2910 without modifying the original"]
2912 pub fn checked_pow(self, mut exp
: u32) -> Option
<Self> {
2913 let mut base
= self;
2914 let mut acc
: Self = 1;
2918 acc
= acc
.checked_mul(base
)?
;
2921 base
= base
.checked_mul(base
)?
;
2924 // Deal with the final bit of the exponent separately, since
2925 // squaring the base afterwards is not necessary and may cause a
2926 // needless overflow.
2928 acc
= acc
.checked_mul(base
)?
;
2936 concat
!("Saturating integer addition. Computes `self + rhs`, saturating at
2937 the numeric bounds instead of overflowing.
2944 ", $Feature
, "assert_eq!(100", stringify
!($SelfT
), ".saturating_add(1), 101);
2945 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature
, "
2948 #[stable(feature = "rust1", since = "1.0.0")]
2949 #[must_use = "this returns the result of the operation, \
2950 without modifying the original"]
2951 #[rustc_const_unstable(feature = "const_saturating_int_methods")]
2953 pub const fn saturating_add(self, rhs
: Self) -> Self {
2954 intrinsics
::saturating_add(self, rhs
)
2959 concat
!("Saturating integer subtraction. Computes `self - rhs`, saturating
2960 at the numeric bounds instead of overflowing.
2967 ", $Feature
, "assert_eq!(100", stringify
!($SelfT
), ".saturating_sub(27), 73);
2968 assert_eq!(13", stringify
!($SelfT
), ".saturating_sub(127), 0);", $EndFeature
, "
2970 #[stable(feature = "rust1", since = "1.0.0")]
2971 #[must_use = "this returns the result of the operation, \
2972 without modifying the original"]
2973 #[rustc_const_unstable(feature = "const_saturating_int_methods")]
2975 pub const fn saturating_sub(self, rhs
: Self) -> Self {
2976 intrinsics
::saturating_sub(self, rhs
)
2981 concat
!("Saturating integer multiplication. Computes `self * rhs`,
2982 saturating at the numeric bounds instead of overflowing.
2989 ", $Feature
, "use std::", stringify
!($SelfT
), ";
2991 assert_eq!(2", stringify
!($SelfT
), ".saturating_mul(10), 20);
2992 assert_eq!((", stringify
!($SelfT
), "::MAX).saturating_mul(10), ", stringify
!($SelfT
),
2993 "::MAX);", $EndFeature
, "
2995 #[stable(feature = "wrapping", since = "1.7.0")]
2996 #[must_use = "this returns the result of the operation, \
2997 without modifying the original"]
2999 pub fn saturating_mul(self, rhs
: Self) -> Self {
3000 self.checked_mul(rhs
).unwrap_or(Self::max_value())
3005 concat
!("Saturating integer exponentiation. Computes `self.pow(exp)`,
3006 saturating at the numeric bounds instead of overflowing.
3013 ", $Feature
, "use std::", stringify
!($SelfT
), ";
3015 assert_eq!(4", stringify
!($SelfT
), ".saturating_pow(3), 64);
3016 assert_eq!(", stringify
!($SelfT
), "::MAX.saturating_pow(2), ", stringify
!($SelfT
), "::MAX);",
3019 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3020 #[must_use = "this returns the result of the operation, \
3021 without modifying the original"]
3023 pub fn saturating_pow(self, exp
: u32) -> Self {
3024 match self.checked_pow(exp
) {
3026 None
=> Self::max_value(),
3032 concat
!("Wrapping (modular) addition. Computes `self + rhs`,
3033 wrapping around at the boundary of the type.
3040 ", $Feature
, "assert_eq!(200", stringify
!($SelfT
), ".wrapping_add(55), 255);
3041 assert_eq!(200", stringify
!($SelfT
), ".wrapping_add(", stringify
!($SelfT
), "::max_value()), 199);",
3044 #[stable(feature = "rust1", since = "1.0.0")]
3045 #[must_use = "this returns the result of the operation, \
3046 without modifying the original"]
3048 pub const fn wrapping_add(self, rhs
: Self) -> Self {
3049 intrinsics
::overflowing_add(self, rhs
)
3054 concat
!("Wrapping (modular) subtraction. Computes `self - rhs`,
3055 wrapping around at the boundary of the type.
3062 ", $Feature
, "assert_eq!(100", stringify
!($SelfT
), ".wrapping_sub(100), 0);
3063 assert_eq!(100", stringify
!($SelfT
), ".wrapping_sub(", stringify
!($SelfT
), "::max_value()), 101);",
3066 #[stable(feature = "rust1", since = "1.0.0")]
3067 #[must_use = "this returns the result of the operation, \
3068 without modifying the original"]
3070 pub const fn wrapping_sub(self, rhs
: Self) -> Self {
3071 intrinsics
::overflowing_sub(self, rhs
)
3075 /// Wrapping (modular) multiplication. Computes `self *
3076 /// rhs`, wrapping around at the boundary of the type.
3082 /// Please note that this example is shared between integer types.
3083 /// Which explains why `u8` is used here.
3086 /// assert_eq!(10u8.wrapping_mul(12), 120);
3087 /// assert_eq!(25u8.wrapping_mul(12), 44);
3089 #[stable(feature = "rust1", since = "1.0.0")]
3090 #[must_use = "this returns the result of the operation, \
3091 without modifying the original"]
3093 pub const fn wrapping_mul(self, rhs
: Self) -> Self {
3094 intrinsics
::overflowing_mul(self, rhs
)
3098 concat
!("Wrapping (modular) division. Computes `self / rhs`.
3099 Wrapped division on unsigned types is just normal division.
3100 There's no way wrapping could ever happen.
3101 This function exists, so that all operations
3102 are accounted for in the wrapping operations.
3109 ", $Feature
, "assert_eq!(100", stringify
!($SelfT
), ".wrapping_div(10), 10);", $EndFeature
, "
3111 #[stable(feature = "num_wrapping", since = "1.2.0")]
3112 #[must_use = "this returns the result of the operation, \
3113 without modifying the original"]
3115 pub fn wrapping_div(self, rhs
: Self) -> Self {
3121 concat
!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
3122 Wrapped division on unsigned types is just normal division.
3123 There's no way wrapping could ever happen.
3124 This function exists, so that all operations
3125 are accounted for in the wrapping operations.
3126 Since, for the positive integers, all common
3127 definitions of division are equal, this
3128 is exactly equal to `self.wrapping_div(rhs)`.
3135 #![feature(euclidean_division)]
3136 assert_eq!(100", stringify
!($SelfT
), ".wrapping_div_euclid(10), 10);
3138 #[unstable(feature = "euclidean_division", issue = "49048")]
3139 #[must_use = "this returns the result of the operation, \
3140 without modifying the original"]
3142 pub fn wrapping_div_euclid(self, rhs
: Self) -> Self {
3148 concat
!("Wrapping (modular) remainder. Computes `self % rhs`.
3149 Wrapped remainder calculation on unsigned types is
3150 just the regular remainder calculation.
3151 There's no way wrapping could ever happen.
3152 This function exists, so that all operations
3153 are accounted for in the wrapping operations.
3160 ", $Feature
, "assert_eq!(100", stringify
!($SelfT
), ".wrapping_rem(10), 0);", $EndFeature
, "
3162 #[stable(feature = "num_wrapping", since = "1.2.0")]
3163 #[must_use = "this returns the result of the operation, \
3164 without modifying the original"]
3166 pub fn wrapping_rem(self, rhs
: Self) -> Self {
3172 concat
!("Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
3173 Wrapped modulo calculation on unsigned types is
3174 just the regular remainder calculation.
3175 There's no way wrapping could ever happen.
3176 This function exists, so that all operations
3177 are accounted for in the wrapping operations.
3178 Since, for the positive integers, all common
3179 definitions of division are equal, this
3180 is exactly equal to `self.wrapping_rem(rhs)`.
3187 #![feature(euclidean_division)]
3188 assert_eq!(100", stringify
!($SelfT
), ".wrapping_rem_euclid(10), 0);
3190 #[unstable(feature = "euclidean_division", issue = "49048")]
3191 #[must_use = "this returns the result of the operation, \
3192 without modifying the original"]
3194 pub fn wrapping_rem_euclid(self, rhs
: Self) -> Self {
3199 /// Wrapping (modular) negation. Computes `-self`,
3200 /// wrapping around at the boundary of the type.
3202 /// Since unsigned types do not have negative equivalents
3203 /// all applications of this function will wrap (except for `-0`).
3204 /// For values smaller than the corresponding signed type's maximum
3205 /// the result is the same as casting the corresponding signed value.
3206 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
3207 /// `MAX` is the corresponding signed type's maximum.
3213 /// Please note that this example is shared between integer types.
3214 /// Which explains why `i8` is used here.
3217 /// assert_eq!(100i8.wrapping_neg(), -100);
3218 /// assert_eq!((-128i8).wrapping_neg(), -128);
3220 #[stable(feature = "num_wrapping", since = "1.2.0")]
3222 pub const fn wrapping_neg(self) -> Self {
3223 self.overflowing_neg().0
3227 concat
!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
3228 where `mask` removes any high-order bits of `rhs` that
3229 would cause the shift to exceed the bitwidth of the type.
3231 Note that this is *not* the same as a rotate-left; the
3232 RHS of a wrapping shift-left is restricted to the range
3233 of the type, rather than the bits shifted out of the LHS
3234 being returned to the other end. The primitive integer
3235 types all implement a `rotate_left` function, which may
3236 be what you want instead.
3243 ", $Feature
, "assert_eq!(1", stringify
!($SelfT
), ".wrapping_shl(7), 128);
3244 assert_eq!(1", stringify
!($SelfT
), ".wrapping_shl(128), 1);", $EndFeature
, "
3246 #[stable(feature = "num_wrapping", since = "1.2.0")]
3247 #[must_use = "this returns the result of the operation, \
3248 without modifying the original"]
3250 pub const fn wrapping_shl(self, rhs
: u32) -> Self {
3252 intrinsics
::unchecked_shl(self, (rhs
& ($BITS
- 1)) as $SelfT
)
3258 concat
!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
3259 where `mask` removes any high-order bits of `rhs` that
3260 would cause the shift to exceed the bitwidth of the type.
3262 Note that this is *not* the same as a rotate-right; the
3263 RHS of a wrapping shift-right is restricted to the range
3264 of the type, rather than the bits shifted out of the LHS
3265 being returned to the other end. The primitive integer
3266 types all implement a `rotate_right` function, which may
3267 be what you want instead.
3274 ", $Feature
, "assert_eq!(128", stringify
!($SelfT
), ".wrapping_shr(7), 1);
3275 assert_eq!(128", stringify
!($SelfT
), ".wrapping_shr(128), 128);", $EndFeature
, "
3277 #[stable(feature = "num_wrapping", since = "1.2.0")]
3278 #[must_use = "this returns the result of the operation, \
3279 without modifying the original"]
3281 pub const fn wrapping_shr(self, rhs
: u32) -> Self {
3283 intrinsics
::unchecked_shr(self, (rhs
& ($BITS
- 1)) as $SelfT
)
3289 concat
!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
3290 wrapping around at the boundary of the type.
3297 ", $Feature
, "assert_eq!(3", stringify
!($SelfT
), ".wrapping_pow(5), 243);
3298 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature
, "
3300 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3301 #[must_use = "this returns the result of the operation, \
3302 without modifying the original"]
3304 pub fn wrapping_pow(self, mut exp
: u32) -> Self {
3305 let mut base
= self;
3306 let mut acc
: Self = 1;
3310 acc
= acc
.wrapping_mul(base
);
3313 base
= base
.wrapping_mul(base
);
3316 // Deal with the final bit of the exponent separately, since
3317 // squaring the base afterwards is not necessary and may cause a
3318 // needless overflow.
3320 acc
= acc
.wrapping_mul(base
);
3328 concat
!("Calculates `self` + `rhs`
3330 Returns a tuple of the addition along with a boolean indicating
3331 whether an arithmetic overflow would occur. If an overflow would
3332 have occurred then the wrapped value is returned.
3339 ", $Feature
, "use std::", stringify
!($SelfT
), ";
3341 assert_eq!(5", stringify
!($SelfT
), ".overflowing_add(2), (7, false));
3342 assert_eq!(", stringify
!($SelfT
), "::MAX.overflowing_add(1), (0, true));", $EndFeature
, "
3344 #[stable(feature = "wrapping", since = "1.7.0")]
3345 #[must_use = "this returns the result of the operation, \
3346 without modifying the original"]
3348 pub const fn overflowing_add(self, rhs
: Self) -> (Self, bool
) {
3349 let (a
, b
) = intrinsics
::add_with_overflow(self as $ActualT
, rhs
as $ActualT
);
3355 concat
!("Calculates `self` - `rhs`
3357 Returns a tuple of the subtraction along with a boolean indicating
3358 whether an arithmetic overflow would occur. If an overflow would
3359 have occurred then the wrapped value is returned.
3366 ", $Feature
, "use std::", stringify
!($SelfT
), ";
3368 assert_eq!(5", stringify
!($SelfT
), ".overflowing_sub(2), (3, false));
3369 assert_eq!(0", stringify
!($SelfT
), ".overflowing_sub(1), (", stringify
!($SelfT
), "::MAX, true));",
3372 #[stable(feature = "wrapping", since = "1.7.0")]
3373 #[must_use = "this returns the result of the operation, \
3374 without modifying the original"]
3376 pub const fn overflowing_sub(self, rhs
: Self) -> (Self, bool
) {
3377 let (a
, b
) = intrinsics
::sub_with_overflow(self as $ActualT
, rhs
as $ActualT
);
3382 /// Calculates the multiplication of `self` and `rhs`.
3384 /// Returns a tuple of the multiplication along with a boolean
3385 /// indicating whether an arithmetic overflow would occur. If an
3386 /// overflow would have occurred then the wrapped value is returned.
3392 /// Please note that this example is shared between integer types.
3393 /// Which explains why `u32` is used here.
3396 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3397 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3399 #[stable(feature = "wrapping", since = "1.7.0")]
3400 #[must_use = "this returns the result of the operation, \
3401 without modifying the original"]
3403 pub const fn overflowing_mul(self, rhs
: Self) -> (Self, bool
) {
3404 let (a
, b
) = intrinsics
::mul_with_overflow(self as $ActualT
, rhs
as $ActualT
);
3409 concat
!("Calculates the divisor when `self` is divided by `rhs`.
3411 Returns a tuple of the divisor along with a boolean indicating
3412 whether an arithmetic overflow would occur. Note that for unsigned
3413 integers overflow never occurs, so the second value is always
3418 This function will panic if `rhs` is 0.
3425 ", $Feature
, "assert_eq!(5", stringify
!($SelfT
), ".overflowing_div(2), (2, false));", $EndFeature
, "
3428 #[stable(feature = "wrapping", since = "1.7.0")]
3429 #[must_use = "this returns the result of the operation, \
3430 without modifying the original"]
3431 pub fn overflowing_div(self, rhs
: Self) -> (Self, bool
) {
3437 concat
!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
3439 Returns a tuple of the divisor along with a boolean indicating
3440 whether an arithmetic overflow would occur. Note that for unsigned
3441 integers overflow never occurs, so the second value is always
3443 Since, for the positive integers, all common
3444 definitions of division are equal, this
3445 is exactly equal to `self.overflowing_div(rhs)`.
3449 This function will panic if `rhs` is 0.
3456 #![feature(euclidean_division)]
3457 assert_eq!(5", stringify
!($SelfT
), ".overflowing_div_euclid(2), (2, false));
3460 #[unstable(feature = "euclidean_division", issue = "49048")]
3461 #[must_use = "this returns the result of the operation, \
3462 without modifying the original"]
3463 pub fn overflowing_div_euclid(self, rhs
: Self) -> (Self, bool
) {
3469 concat
!("Calculates the remainder when `self` is divided by `rhs`.
3471 Returns a tuple of the remainder after dividing along with a boolean
3472 indicating whether an arithmetic overflow would occur. Note that for
3473 unsigned integers overflow never occurs, so the second value is
3478 This function will panic if `rhs` is 0.
3485 ", $Feature
, "assert_eq!(5", stringify
!($SelfT
), ".overflowing_rem(2), (1, false));", $EndFeature
, "
3488 #[stable(feature = "wrapping", since = "1.7.0")]
3489 #[must_use = "this returns the result of the operation, \
3490 without modifying the original"]
3491 pub fn overflowing_rem(self, rhs
: Self) -> (Self, bool
) {
3497 concat
!("Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
3499 Returns a tuple of the modulo after dividing along with a boolean
3500 indicating whether an arithmetic overflow would occur. Note that for
3501 unsigned integers overflow never occurs, so the second value is
3503 Since, for the positive integers, all common
3504 definitions of division are equal, this operation
3505 is exactly equal to `self.overflowing_rem(rhs)`.
3509 This function will panic if `rhs` is 0.
3516 #![feature(euclidean_division)]
3517 assert_eq!(5", stringify
!($SelfT
), ".overflowing_rem_euclid(2), (1, false));
3520 #[unstable(feature = "euclidean_division", issue = "49048")]
3521 #[must_use = "this returns the result of the operation, \
3522 without modifying the original"]
3523 pub fn overflowing_rem_euclid(self, rhs
: Self) -> (Self, bool
) {
3529 concat
!("Negates self in an overflowing fashion.
3531 Returns `!self + 1` using wrapping operations to return the value
3532 that represents the negation of this unsigned value. Note that for
3533 positive unsigned values overflow always occurs, but negating 0 does
3541 ", $Feature
, "assert_eq!(0", stringify
!($SelfT
), ".overflowing_neg(), (0, false));
3542 assert_eq!(2", stringify
!($SelfT
), ".overflowing_neg(), (-2i32 as ", stringify
!($SelfT
),
3543 ", true));", $EndFeature
, "
3546 #[stable(feature = "wrapping", since = "1.7.0")]
3547 pub const fn overflowing_neg(self) -> (Self, bool
) {
3548 ((!self).wrapping_add(1), self != 0)
3553 concat
!("Shifts self left by `rhs` bits.
3555 Returns a tuple of the shifted version of self along with a boolean
3556 indicating whether the shift value was larger than or equal to the
3557 number of bits. If the shift value is too large, then value is
3558 masked (N-1) where N is the number of bits, and this value is then
3559 used to perform the shift.
3566 ", $Feature
, "assert_eq!(0x1", stringify
!($SelfT
), ".overflowing_shl(4), (0x10, false));
3567 assert_eq!(0x1", stringify
!($SelfT
), ".overflowing_shl(132), (0x10, true));", $EndFeature
, "
3569 #[stable(feature = "wrapping", since = "1.7.0")]
3570 #[must_use = "this returns the result of the operation, \
3571 without modifying the original"]
3573 pub const fn overflowing_shl(self, rhs
: u32) -> (Self, bool
) {
3574 (self.wrapping_shl(rhs
), (rhs
> ($BITS
- 1)))
3579 concat
!("Shifts self right by `rhs` bits.
3581 Returns a tuple of the shifted version of self along with a boolean
3582 indicating whether the shift value was larger than or equal to the
3583 number of bits. If the shift value is too large, then value is
3584 masked (N-1) where N is the number of bits, and this value is then
3585 used to perform the shift.
3592 ", $Feature
, "assert_eq!(0x10", stringify
!($SelfT
), ".overflowing_shr(4), (0x1, false));
3593 assert_eq!(0x10", stringify
!($SelfT
), ".overflowing_shr(132), (0x1, true));", $EndFeature
, "
3595 #[stable(feature = "wrapping", since = "1.7.0")]
3596 #[must_use = "this returns the result of the operation, \
3597 without modifying the original"]
3599 pub const fn overflowing_shr(self, rhs
: u32) -> (Self, bool
) {
3600 (self.wrapping_shr(rhs
), (rhs
> ($BITS
- 1)))
3605 concat
!("Raises self to the power of `exp`, using exponentiation by squaring.
3607 Returns a tuple of the exponentiation along with a bool indicating
3608 whether an overflow happened.
3615 ", $Feature
, "assert_eq!(3", stringify
!($SelfT
), ".overflowing_pow(5), (243, false));
3616 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature
, "
3618 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3619 #[must_use = "this returns the result of the operation, \
3620 without modifying the original"]
3622 pub fn overflowing_pow(self, mut exp
: u32) -> (Self, bool
) {
3623 let mut base
= self;
3624 let mut acc
: Self = 1;
3625 let mut overflown
= false;
3626 // Scratch space for storing results of overflowing_mul.
3631 r
= acc
.overflowing_mul(base
);
3636 r
= base
.overflowing_mul(base
);
3641 // Deal with the final bit of the exponent separately, since
3642 // squaring the base afterwards is not necessary and may cause a
3643 // needless overflow.
3645 r
= acc
.overflowing_mul(base
);
3655 concat
!("Raises self to the power of `exp`, using exponentiation by squaring.
3662 ", $Feature
, "assert_eq!(2", stringify
!($SelfT
), ".pow(5), 32);", $EndFeature
, "
3664 #[stable(feature = "rust1", since = "1.0.0")]
3665 #[must_use = "this returns the result of the operation, \
3666 without modifying the original"]
3668 #[rustc_inherit_overflow_checks]
3669 pub fn pow(self, mut exp
: u32) -> Self {
3670 let mut base
= self;
3681 // Deal with the final bit of the exponent separately, since
3682 // squaring the base afterwards is not necessary and may cause a
3683 // needless overflow.
3693 concat
!("Performs Euclidean division.
3695 Since, for the positive integers, all common
3696 definitions of division are equal, this
3697 is exactly equal to `self / rhs`.
3704 #![feature(euclidean_division)]
3705 assert_eq!(7", stringify
!($SelfT
), ".div_euclid(4), 1); // or any other integer type
3707 #[unstable(feature = "euclidean_division", issue = "49048")]
3708 #[must_use = "this returns the result of the operation, \
3709 without modifying the original"]
3711 #[rustc_inherit_overflow_checks]
3712 pub fn div_euclid(self, rhs
: Self) -> Self {
3719 concat
!("Calculates the least remainder of `self (mod rhs)`.
3721 Since, for the positive integers, all common
3722 definitions of division are equal, this
3723 is exactly equal to `self % rhs`.
3730 #![feature(euclidean_division)]
3731 assert_eq!(7", stringify
!($SelfT
), ".rem_euclid(4), 3); // or any other integer type
3733 #[unstable(feature = "euclidean_division", issue = "49048")]
3734 #[must_use = "this returns the result of the operation, \
3735 without modifying the original"]
3737 #[rustc_inherit_overflow_checks]
3738 pub fn rem_euclid(self, rhs
: Self) -> Self {
3744 concat
!("Returns `true` if and only if `self == 2^k` for some `k`.
3751 ", $Feature
, "assert!(16", stringify
!($SelfT
), ".is_power_of_two());
3752 assert!(!10", stringify
!($SelfT
), ".is_power_of_two());", $EndFeature
, "
3754 #[stable(feature = "rust1", since = "1.0.0")]
3756 pub fn is_power_of_two(self) -> bool
{
3757 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
3761 // Returns one less than next power of two.
3762 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
3764 // 8u8.one_less_than_next_power_of_two() == 7
3765 // 6u8.one_less_than_next_power_of_two() == 7
3767 // This method cannot overflow, as in the `next_power_of_two`
3768 // overflow cases it instead ends up returning the maximum value
3769 // of the type, and can return 0 for 0.
3771 fn one_less_than_next_power_of_two(self) -> Self {
3772 if self <= 1 { return 0; }
3774 // Because `p > 0`, it cannot consist entirely of leading zeros.
3775 // That means the shift is always in-bounds, and some processors
3776 // (such as intel pre-haswell) have more efficient ctlz
3777 // intrinsics when the argument is non-zero.
3779 let z
= unsafe { intrinsics::ctlz_nonzero(p) }
;
3780 <$SelfT
>::max_value() >> z
3784 concat
!("Returns the smallest power of two greater than or equal to `self`.
3786 When return value overflows (i.e., `self > (1 << (N-1))` for type
3787 `uN`), it panics in debug mode and return value is wrapped to 0 in
3788 release mode (the only situation in which method can return 0).
3795 ", $Feature
, "assert_eq!(2", stringify
!($SelfT
), ".next_power_of_two(), 2);
3796 assert_eq!(3", stringify
!($SelfT
), ".next_power_of_two(), 4);", $EndFeature
, "
3798 #[stable(feature = "rust1", since = "1.0.0")]
3800 pub fn next_power_of_two(self) -> Self {
3801 // Call the trait to get overflow checks
3802 ops
::Add
::add(self.one_less_than_next_power_of_two(), 1)
3807 concat
!("Returns the smallest power of two greater than or equal to `n`. If
3808 the next power of two is greater than the type's maximum value,
3809 `None` is returned, otherwise the power of two is wrapped in `Some`.
3816 ", $Feature
, "assert_eq!(2", stringify
!($SelfT
),
3817 ".checked_next_power_of_two(), Some(2));
3818 assert_eq!(3", stringify
!($SelfT
), ".checked_next_power_of_two(), Some(4));
3819 assert_eq!(", stringify
!($SelfT
), "::max_value().checked_next_power_of_two(), None);",
3823 #[stable(feature = "rust1", since = "1.0.0")]
3824 pub fn checked_next_power_of_two(self) -> Option
<Self> {
3825 self.one_less_than_next_power_of_two().checked_add(1)
3830 concat
!("Returns the smallest power of two greater than or equal to `n`. If
3831 the next power of two is greater than the type's maximum value,
3832 the return value is wrapped to `0`.
3839 #![feature(wrapping_next_power_of_two)]
3841 assert_eq!(2", stringify
!($SelfT
), ".wrapping_next_power_of_two(), 2);
3842 assert_eq!(3", stringify
!($SelfT
), ".wrapping_next_power_of_two(), 4);
3843 assert_eq!(", stringify
!($SelfT
), "::max_value().wrapping_next_power_of_two(), 0);",
3846 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
3847 reason
= "needs decision on wrapping behaviour")]
3848 pub fn wrapping_next_power_of_two(self) -> Self {
3849 self.one_less_than_next_power_of_two().wrapping_add(1)
3854 concat
!("Return the memory representation of this integer as a byte array in
3855 big-endian (network) byte order.
3862 let bytes = ", $swap_op
, stringify
!($SelfT
), ".to_be_bytes();
3863 assert_eq!(bytes, ", $be_bytes
, ");
3865 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3866 #[rustc_const_unstable(feature = "const_int_conversion")]
3868 pub const fn to_be_bytes(self) -> [u8; mem
::size_of
::<Self>()] {
3869 self.to_be().to_ne_bytes()
3874 concat
!("Return the memory representation of this integer as a byte array in
3875 little-endian byte order.
3882 let bytes = ", $swap_op
, stringify
!($SelfT
), ".to_le_bytes();
3883 assert_eq!(bytes, ", $le_bytes
, ");
3885 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3886 #[rustc_const_unstable(feature = "const_int_conversion")]
3888 pub const fn to_le_bytes(self) -> [u8; mem
::size_of
::<Self>()] {
3889 self.to_le().to_ne_bytes()
3895 Return the memory representation of this integer as a byte array in
3898 As the target platform's native endianness is used, portable code
3899 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
3904 [`to_be_bytes`]: #method.to_be_bytes
3905 [`to_le_bytes`]: #method.to_le_bytes
3910 let bytes = ", $swap_op
, stringify
!($SelfT
), ".to_ne_bytes();
3911 assert_eq!(bytes, if cfg!(target_endian = \"big\") {
3917 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3918 #[rustc_const_unstable(feature = "const_int_conversion")]
3920 pub const fn to_ne_bytes(self) -> [u8; mem
::size_of
::<Self>()] {
3921 unsafe { mem::transmute(self) }
3926 concat
!("Create an integer value from its representation as a byte array in
3934 let value = ", stringify
!($SelfT
), "::from_be_bytes(", $be_bytes
, ");
3935 assert_eq!(value, ", $swap_op
, ");
3938 When starting from a slice rather than an array, fallible conversion APIs can be used:
3941 use std::convert::TryInto;
3943 fn read_be_", stringify
!($SelfT
), "(input: &mut &[u8]) -> ", stringify
!($SelfT
), " {
3944 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify
!($SelfT
), ">());
3946 ", stringify
!($SelfT
), "::from_be_bytes(int_bytes.try_into().unwrap())
3949 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3950 #[rustc_const_unstable(feature = "const_int_conversion")]
3952 pub const fn from_be_bytes(bytes
: [u8; mem
::size_of
::<Self>()]) -> Self {
3953 Self::from_be(Self::from_ne_bytes(bytes
))
3959 Create an integer value from its representation as a byte array in
3967 let value = ", stringify
!($SelfT
), "::from_le_bytes(", $le_bytes
, ");
3968 assert_eq!(value, ", $swap_op
, ");
3971 When starting from a slice rather than an array, fallible conversion APIs can be used:
3974 use std::convert::TryInto;
3976 fn read_le_", stringify
!($SelfT
), "(input: &mut &[u8]) -> ", stringify
!($SelfT
), " {
3977 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify
!($SelfT
), ">());
3979 ", stringify
!($SelfT
), "::from_le_bytes(int_bytes.try_into().unwrap())
3982 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3983 #[rustc_const_unstable(feature = "const_int_conversion")]
3985 pub const fn from_le_bytes(bytes
: [u8; mem
::size_of
::<Self>()]) -> Self {
3986 Self::from_le(Self::from_ne_bytes(bytes
))
3991 concat
!("Create an integer value from its memory representation as a byte
3992 array in native endianness.
3994 As the target platform's native endianness is used, portable code
3995 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
3996 appropriate instead.
3998 [`from_be_bytes`]: #method.from_be_bytes
3999 [`from_le_bytes`]: #method.from_le_bytes
4006 let value = ", stringify
!($SelfT
), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
4011 assert_eq!(value, ", $swap_op
, ");
4014 When starting from a slice rather than an array, fallible conversion APIs can be used:
4017 use std::convert::TryInto;
4019 fn read_ne_", stringify
!($SelfT
), "(input: &mut &[u8]) -> ", stringify
!($SelfT
), " {
4020 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify
!($SelfT
), ">());
4022 ", stringify
!($SelfT
), "::from_ne_bytes(int_bytes.try_into().unwrap())
4025 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
4026 #[rustc_const_unstable(feature = "const_int_conversion")]
4028 pub const fn from_ne_bytes(bytes
: [u8; mem
::size_of
::<Self>()]) -> Self {
4029 unsafe { mem::transmute(bytes) }
4037 uint_impl
! { u8, u8, 8, 255, "", "", 2, "0x82", "0xa", "0x12", "0x12", "0x48", "[0x12]",
4041 /// Checks if the value is within the ASCII range.
4046 /// let ascii = 97u8;
4047 /// let non_ascii = 150u8;
4049 /// assert!(ascii.is_ascii());
4050 /// assert!(!non_ascii.is_ascii());
4052 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4054 pub fn is_ascii(&self) -> bool
{
4058 /// Makes a copy of the value in its ASCII upper case equivalent.
4060 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4061 /// but non-ASCII letters are unchanged.
4063 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
4068 /// let lowercase_a = 97u8;
4070 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
4073 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
4074 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4076 pub fn to_ascii_uppercase(&self) -> u8 {
4077 // Unset the fith bit if this is a lowercase letter
4078 *self & !((self.is_ascii_lowercase() as u8) << 5)
4081 /// Makes a copy of the value in its ASCII lower case equivalent.
4083 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4084 /// but non-ASCII letters are unchanged.
4086 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
4091 /// let uppercase_a = 65u8;
4093 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
4096 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
4097 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4099 pub fn to_ascii_lowercase(&self) -> u8 {
4100 // Set the fith bit if this is an uppercase letter
4101 *self | ((self.is_ascii_uppercase() as u8) << 5)
4104 /// Checks that two values are an ASCII case-insensitive match.
4106 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
4111 /// let lowercase_a = 97u8;
4112 /// let uppercase_a = 65u8;
4114 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
4116 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4118 pub fn eq_ignore_ascii_case(&self, other
: &u8) -> bool
{
4119 self.to_ascii_lowercase() == other
.to_ascii_lowercase()
4122 /// Converts this value to its ASCII upper case equivalent in-place.
4124 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4125 /// but non-ASCII letters are unchanged.
4127 /// To return a new uppercased value without modifying the existing one, use
4128 /// [`to_ascii_uppercase`].
4133 /// let mut byte = b'a';
4135 /// byte.make_ascii_uppercase();
4137 /// assert_eq!(b'A', byte);
4140 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
4141 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4143 pub fn make_ascii_uppercase(&mut self) {
4144 *self = self.to_ascii_uppercase();
4147 /// Converts this value to its ASCII lower case equivalent in-place.
4149 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4150 /// but non-ASCII letters are unchanged.
4152 /// To return a new lowercased value without modifying the existing one, use
4153 /// [`to_ascii_lowercase`].
4158 /// let mut byte = b'A';
4160 /// byte.make_ascii_lowercase();
4162 /// assert_eq!(b'a', byte);
4165 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
4166 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4168 pub fn make_ascii_lowercase(&mut self) {
4169 *self = self.to_ascii_lowercase();
4172 /// Checks if the value is an ASCII alphabetic character:
4174 /// - U+0041 'A' ... U+005A 'Z', or
4175 /// - U+0061 'a' ... U+007A 'z'.
4180 /// let uppercase_a = b'A';
4181 /// let uppercase_g = b'G';
4184 /// let zero = b'0';
4185 /// let percent = b'%';
4186 /// let space = b' ';
4188 /// let esc = 0x1b_u8;
4190 /// assert!(uppercase_a.is_ascii_alphabetic());
4191 /// assert!(uppercase_g.is_ascii_alphabetic());
4192 /// assert!(a.is_ascii_alphabetic());
4193 /// assert!(g.is_ascii_alphabetic());
4194 /// assert!(!zero.is_ascii_alphabetic());
4195 /// assert!(!percent.is_ascii_alphabetic());
4196 /// assert!(!space.is_ascii_alphabetic());
4197 /// assert!(!lf.is_ascii_alphabetic());
4198 /// assert!(!esc.is_ascii_alphabetic());
4200 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4202 pub fn is_ascii_alphabetic(&self) -> bool
{
4204 b'A'
..=b'Z'
| b'a'
..=b'z'
=> true,
4209 /// Checks if the value is an ASCII uppercase character:
4210 /// U+0041 'A' ... U+005A 'Z'.
4215 /// let uppercase_a = b'A';
4216 /// let uppercase_g = b'G';
4219 /// let zero = b'0';
4220 /// let percent = b'%';
4221 /// let space = b' ';
4223 /// let esc = 0x1b_u8;
4225 /// assert!(uppercase_a.is_ascii_uppercase());
4226 /// assert!(uppercase_g.is_ascii_uppercase());
4227 /// assert!(!a.is_ascii_uppercase());
4228 /// assert!(!g.is_ascii_uppercase());
4229 /// assert!(!zero.is_ascii_uppercase());
4230 /// assert!(!percent.is_ascii_uppercase());
4231 /// assert!(!space.is_ascii_uppercase());
4232 /// assert!(!lf.is_ascii_uppercase());
4233 /// assert!(!esc.is_ascii_uppercase());
4235 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4237 pub fn is_ascii_uppercase(&self) -> bool
{
4239 b'A'
..=b'Z'
=> true,
4244 /// Checks if the value is an ASCII lowercase character:
4245 /// U+0061 'a' ... U+007A 'z'.
4250 /// let uppercase_a = b'A';
4251 /// let uppercase_g = b'G';
4254 /// let zero = b'0';
4255 /// let percent = b'%';
4256 /// let space = b' ';
4258 /// let esc = 0x1b_u8;
4260 /// assert!(!uppercase_a.is_ascii_lowercase());
4261 /// assert!(!uppercase_g.is_ascii_lowercase());
4262 /// assert!(a.is_ascii_lowercase());
4263 /// assert!(g.is_ascii_lowercase());
4264 /// assert!(!zero.is_ascii_lowercase());
4265 /// assert!(!percent.is_ascii_lowercase());
4266 /// assert!(!space.is_ascii_lowercase());
4267 /// assert!(!lf.is_ascii_lowercase());
4268 /// assert!(!esc.is_ascii_lowercase());
4270 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4272 pub fn is_ascii_lowercase(&self) -> bool
{
4274 b'a'
..=b'z'
=> true,
4279 /// Checks if the value is an ASCII alphanumeric character:
4281 /// - U+0041 'A' ... U+005A 'Z', or
4282 /// - U+0061 'a' ... U+007A 'z', or
4283 /// - U+0030 '0' ... U+0039 '9'.
4288 /// let uppercase_a = b'A';
4289 /// let uppercase_g = b'G';
4292 /// let zero = b'0';
4293 /// let percent = b'%';
4294 /// let space = b' ';
4296 /// let esc = 0x1b_u8;
4298 /// assert!(uppercase_a.is_ascii_alphanumeric());
4299 /// assert!(uppercase_g.is_ascii_alphanumeric());
4300 /// assert!(a.is_ascii_alphanumeric());
4301 /// assert!(g.is_ascii_alphanumeric());
4302 /// assert!(zero.is_ascii_alphanumeric());
4303 /// assert!(!percent.is_ascii_alphanumeric());
4304 /// assert!(!space.is_ascii_alphanumeric());
4305 /// assert!(!lf.is_ascii_alphanumeric());
4306 /// assert!(!esc.is_ascii_alphanumeric());
4308 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4310 pub fn is_ascii_alphanumeric(&self) -> bool
{
4312 b'
0'
..=b'
9'
| b'A'
..=b'Z'
| b'a'
..=b'z'
=> true,
4317 /// Checks if the value is an ASCII decimal digit:
4318 /// U+0030 '0' ... U+0039 '9'.
4323 /// let uppercase_a = b'A';
4324 /// let uppercase_g = b'G';
4327 /// let zero = b'0';
4328 /// let percent = b'%';
4329 /// let space = b' ';
4331 /// let esc = 0x1b_u8;
4333 /// assert!(!uppercase_a.is_ascii_digit());
4334 /// assert!(!uppercase_g.is_ascii_digit());
4335 /// assert!(!a.is_ascii_digit());
4336 /// assert!(!g.is_ascii_digit());
4337 /// assert!(zero.is_ascii_digit());
4338 /// assert!(!percent.is_ascii_digit());
4339 /// assert!(!space.is_ascii_digit());
4340 /// assert!(!lf.is_ascii_digit());
4341 /// assert!(!esc.is_ascii_digit());
4343 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4345 pub fn is_ascii_digit(&self) -> bool
{
4347 b'
0'
..=b'
9'
=> true,
4352 /// Checks if the value is an ASCII hexadecimal digit:
4354 /// - U+0030 '0' ... U+0039 '9', or
4355 /// - U+0041 'A' ... U+0046 'F', or
4356 /// - U+0061 'a' ... U+0066 'f'.
4361 /// let uppercase_a = b'A';
4362 /// let uppercase_g = b'G';
4365 /// let zero = b'0';
4366 /// let percent = b'%';
4367 /// let space = b' ';
4369 /// let esc = 0x1b_u8;
4371 /// assert!(uppercase_a.is_ascii_hexdigit());
4372 /// assert!(!uppercase_g.is_ascii_hexdigit());
4373 /// assert!(a.is_ascii_hexdigit());
4374 /// assert!(!g.is_ascii_hexdigit());
4375 /// assert!(zero.is_ascii_hexdigit());
4376 /// assert!(!percent.is_ascii_hexdigit());
4377 /// assert!(!space.is_ascii_hexdigit());
4378 /// assert!(!lf.is_ascii_hexdigit());
4379 /// assert!(!esc.is_ascii_hexdigit());
4381 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4383 pub fn is_ascii_hexdigit(&self) -> bool
{
4385 b'
0'
..=b'
9'
| b'A'
..=b'F'
| b'a'
..=b'f'
=> true,
4390 /// Checks if the value is an ASCII punctuation character:
4392 /// - U+0021 ... U+002F `! " # $ % & ' ( ) * + , - . /`, or
4393 /// - U+003A ... U+0040 `: ; < = > ? @`, or
4394 /// - U+005B ... U+0060 ``[ \ ] ^ _ ` ``, or
4395 /// - U+007B ... U+007E `{ | } ~`
4400 /// let uppercase_a = b'A';
4401 /// let uppercase_g = b'G';
4404 /// let zero = b'0';
4405 /// let percent = b'%';
4406 /// let space = b' ';
4408 /// let esc = 0x1b_u8;
4410 /// assert!(!uppercase_a.is_ascii_punctuation());
4411 /// assert!(!uppercase_g.is_ascii_punctuation());
4412 /// assert!(!a.is_ascii_punctuation());
4413 /// assert!(!g.is_ascii_punctuation());
4414 /// assert!(!zero.is_ascii_punctuation());
4415 /// assert!(percent.is_ascii_punctuation());
4416 /// assert!(!space.is_ascii_punctuation());
4417 /// assert!(!lf.is_ascii_punctuation());
4418 /// assert!(!esc.is_ascii_punctuation());
4420 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4422 pub fn is_ascii_punctuation(&self) -> bool
{
4424 b'
!'
..=b'
/'
| b'
:'
..=b'@'
| b'
['
..=b'`'
| b'
{'
..=b'
~'
=> true,
4429 /// Checks if the value is an ASCII graphic character:
4430 /// U+0021 '!' ... U+007E '~'.
4435 /// let uppercase_a = b'A';
4436 /// let uppercase_g = b'G';
4439 /// let zero = b'0';
4440 /// let percent = b'%';
4441 /// let space = b' ';
4443 /// let esc = 0x1b_u8;
4445 /// assert!(uppercase_a.is_ascii_graphic());
4446 /// assert!(uppercase_g.is_ascii_graphic());
4447 /// assert!(a.is_ascii_graphic());
4448 /// assert!(g.is_ascii_graphic());
4449 /// assert!(zero.is_ascii_graphic());
4450 /// assert!(percent.is_ascii_graphic());
4451 /// assert!(!space.is_ascii_graphic());
4452 /// assert!(!lf.is_ascii_graphic());
4453 /// assert!(!esc.is_ascii_graphic());
4455 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4457 pub fn is_ascii_graphic(&self) -> bool
{
4459 b'
!'
..=b'
~'
=> true,
4464 /// Checks if the value is an ASCII whitespace character:
4465 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
4466 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
4468 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
4469 /// whitespace][infra-aw]. There are several other definitions in
4470 /// wide use. For instance, [the POSIX locale][pct] includes
4471 /// U+000B VERTICAL TAB as well as all the above characters,
4472 /// but—from the very same specification—[the default rule for
4473 /// "field splitting" in the Bourne shell][bfs] considers *only*
4474 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
4476 /// If you are writing a program that will process an existing
4477 /// file format, check what that format's definition of whitespace is
4478 /// before using this function.
4480 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
4481 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
4482 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
4487 /// let uppercase_a = b'A';
4488 /// let uppercase_g = b'G';
4491 /// let zero = b'0';
4492 /// let percent = b'%';
4493 /// let space = b' ';
4495 /// let esc = 0x1b_u8;
4497 /// assert!(!uppercase_a.is_ascii_whitespace());
4498 /// assert!(!uppercase_g.is_ascii_whitespace());
4499 /// assert!(!a.is_ascii_whitespace());
4500 /// assert!(!g.is_ascii_whitespace());
4501 /// assert!(!zero.is_ascii_whitespace());
4502 /// assert!(!percent.is_ascii_whitespace());
4503 /// assert!(space.is_ascii_whitespace());
4504 /// assert!(lf.is_ascii_whitespace());
4505 /// assert!(!esc.is_ascii_whitespace());
4507 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4509 pub fn is_ascii_whitespace(&self) -> bool
{
4511 b'
\t'
| b'
\n'
| b'
\x0C'
| b'
\r'
| b' '
=> true,
4516 /// Checks if the value is an ASCII control character:
4517 /// U+0000 NUL ... U+001F UNIT SEPARATOR, or U+007F DELETE.
4518 /// Note that most ASCII whitespace characters are control
4519 /// characters, but SPACE is not.
4524 /// let uppercase_a = b'A';
4525 /// let uppercase_g = b'G';
4528 /// let zero = b'0';
4529 /// let percent = b'%';
4530 /// let space = b' ';
4532 /// let esc = 0x1b_u8;
4534 /// assert!(!uppercase_a.is_ascii_control());
4535 /// assert!(!uppercase_g.is_ascii_control());
4536 /// assert!(!a.is_ascii_control());
4537 /// assert!(!g.is_ascii_control());
4538 /// assert!(!zero.is_ascii_control());
4539 /// assert!(!percent.is_ascii_control());
4540 /// assert!(!space.is_ascii_control());
4541 /// assert!(lf.is_ascii_control());
4542 /// assert!(esc.is_ascii_control());
4544 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4546 pub fn is_ascii_control(&self) -> bool
{
4548 b'
\0'
..=b'
\x1F'
| b'
\x7F'
=> true,
4556 uint_impl
! { u16, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4557 "[0x34, 0x12]", "[0x12, 0x34]", "", "" }
4562 uint_impl
! { u32, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4563 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]", "", "" }
4568 uint_impl
! { u64, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4569 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4570 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4571 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
4577 uint_impl
! { u128
, u128
, 128, 340282366920938463463374607431768211455, "", "", 16,
4578 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
4579 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
4580 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
4581 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4582 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
4583 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
4587 #[cfg(target_pointer_width = "16")]
4590 uint_impl
! { usize, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4591 "[0x34, 0x12]", "[0x12, 0x34]",
4592 usize_isize_to_xe_bytes_doc
!(), usize_isize_from_xe_bytes_doc
!() }
4594 #[cfg(target_pointer_width = "32")]
4597 uint_impl
! { usize, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4598 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]",
4599 usize_isize_to_xe_bytes_doc
!(), usize_isize_from_xe_bytes_doc
!() }
4602 #[cfg(target_pointer_width = "64")]
4605 uint_impl
! { usize, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4606 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4607 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4608 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
4609 usize_isize_to_xe_bytes_doc
!(), usize_isize_from_xe_bytes_doc
!() }
4612 /// A classification of floating point numbers.
4614 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
4615 /// their documentation for more.
4617 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
4618 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
4623 /// use std::num::FpCategory;
4626 /// let num = 12.4_f32;
4627 /// let inf = f32::INFINITY;
4628 /// let zero = 0f32;
4629 /// let sub: f32 = 1.1754942e-38;
4630 /// let nan = f32::NAN;
4632 /// assert_eq!(num.classify(), FpCategory::Normal);
4633 /// assert_eq!(inf.classify(), FpCategory::Infinite);
4634 /// assert_eq!(zero.classify(), FpCategory::Zero);
4635 /// assert_eq!(nan.classify(), FpCategory::Nan);
4636 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
4638 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
4639 #[stable(feature = "rust1", since = "1.0.0")]
4640 pub enum FpCategory
{
4641 /// "Not a Number", often obtained by dividing by zero.
4642 #[stable(feature = "rust1", since = "1.0.0")]
4645 /// Positive or negative infinity.
4646 #[stable(feature = "rust1", since = "1.0.0")]
4649 /// Positive or negative zero.
4650 #[stable(feature = "rust1", since = "1.0.0")]
4653 /// De-normalized floating point representation (less precise than `Normal`).
4654 #[stable(feature = "rust1", since = "1.0.0")]
4657 /// A regular floating point number.
4658 #[stable(feature = "rust1", since = "1.0.0")]
4662 macro_rules
! from_str_radix_int_impl
{
4664 #[stable(feature = "rust1", since = "1.0.0")]
4665 impl FromStr
for $t
{
4666 type Err
= ParseIntError
;
4667 fn from_str(src
: &str) -> Result
<Self, ParseIntError
> {
4668 from_str_radix(src
, 10)
4673 from_str_radix_int_impl
! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
4675 /// The error type returned when a checked integral type conversion fails.
4676 #[stable(feature = "try_from", since = "1.34.0")]
4677 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
4678 pub struct TryFromIntError(());
4680 impl TryFromIntError
{
4681 #[unstable(feature = "int_error_internals",
4682 reason
= "available through Error trait and this method should \
4683 not be exposed publicly",
4686 pub fn __description(&self) -> &str {
4687 "out of range integral type conversion attempted"
4691 #[stable(feature = "try_from", since = "1.34.0")]
4692 impl fmt
::Display
for TryFromIntError
{
4693 fn fmt(&self, fmt
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
4694 self.__description().fmt(fmt
)
4698 #[stable(feature = "try_from", since = "1.34.0")]
4699 impl From
<Infallible
> for TryFromIntError
{
4700 fn from(x
: Infallible
) -> TryFromIntError
{
4705 #[unstable(feature = "never_type", issue = "35121")]
4706 impl From
<!> for TryFromIntError
{
4707 fn from(never
: !) -> TryFromIntError
{
4708 // Match rather than coerce to make sure that code like
4709 // `From<Infallible> for TryFromIntError` above will keep working
4710 // when `Infallible` becomes an alias to `!`.
4715 // no possible bounds violation
4716 macro_rules
! try_from_unbounded
{
4717 ($source
:ty
, $
($target
:ty
),*) => {$
(
4718 #[stable(feature = "try_from", since = "1.34.0")]
4719 impl TryFrom
<$source
> for $target
{
4720 type Error
= TryFromIntError
;
4722 /// Try to create the target number type from a source
4723 /// number type. This returns an error if the source value
4724 /// is outside of the range of the target type.
4726 fn try_from(value
: $source
) -> Result
<Self, Self::Error
> {
4727 Ok(value
as $target
)
4733 // only negative bounds
4734 macro_rules
! try_from_lower_bounded
{
4735 ($source
:ty
, $
($target
:ty
),*) => {$
(
4736 #[stable(feature = "try_from", since = "1.34.0")]
4737 impl TryFrom
<$source
> for $target
{
4738 type Error
= TryFromIntError
;
4740 /// Try to create the target number type from a source
4741 /// number type. This returns an error if the source value
4742 /// is outside of the range of the target type.
4744 fn try_from(u
: $source
) -> Result
<$target
, TryFromIntError
> {
4748 Err(TryFromIntError(()))
4755 // unsigned to signed (only positive bound)
4756 macro_rules
! try_from_upper_bounded
{
4757 ($source
:ty
, $
($target
:ty
),*) => {$
(
4758 #[stable(feature = "try_from", since = "1.34.0")]
4759 impl TryFrom
<$source
> for $target
{
4760 type Error
= TryFromIntError
;
4762 /// Try to create the target number type from a source
4763 /// number type. This returns an error if the source value
4764 /// is outside of the range of the target type.
4766 fn try_from(u
: $source
) -> Result
<$target
, TryFromIntError
> {
4767 if u
> (<$target
>::max_value() as $source
) {
4768 Err(TryFromIntError(()))
4778 macro_rules
! try_from_both_bounded
{
4779 ($source
:ty
, $
($target
:ty
),*) => {$
(
4780 #[stable(feature = "try_from", since = "1.34.0")]
4781 impl TryFrom
<$source
> for $target
{
4782 type Error
= TryFromIntError
;
4784 /// Try to create the target number type from a source
4785 /// number type. This returns an error if the source value
4786 /// is outside of the range of the target type.
4788 fn try_from(u
: $source
) -> Result
<$target
, TryFromIntError
> {
4789 let min
= <$target
>::min_value() as $source
;
4790 let max
= <$target
>::max_value() as $source
;
4791 if u
< min
|| u
> max
{
4792 Err(TryFromIntError(()))
4802 ($mac
:ident
, $source
:ty
, $
($target
:ty
),*) => {$
(
4803 $mac
!($target
, $source
);
4807 // intra-sign conversions
4808 try_from_upper_bounded
!(u16, u8);
4809 try_from_upper_bounded
!(u32, u16, u8);
4810 try_from_upper_bounded
!(u64, u32, u16, u8);
4811 try_from_upper_bounded
!(u128
, u64, u32, u16, u8);
4813 try_from_both_bounded
!(i16, i8);
4814 try_from_both_bounded
!(i32, i16, i8);
4815 try_from_both_bounded
!(i64, i32, i16, i8);
4816 try_from_both_bounded
!(i128
, i64, i32, i16, i8);
4818 // unsigned-to-signed
4819 try_from_upper_bounded
!(u8, i8);
4820 try_from_upper_bounded
!(u16, i8, i16);
4821 try_from_upper_bounded
!(u32, i8, i16, i32);
4822 try_from_upper_bounded
!(u64, i8, i16, i32, i64);
4823 try_from_upper_bounded
!(u128
, i8, i16, i32, i64, i128
);
4825 // signed-to-unsigned
4826 try_from_lower_bounded
!(i8, u8, u16, u32, u64, u128
);
4827 try_from_lower_bounded
!(i16, u16, u32, u64, u128
);
4828 try_from_lower_bounded
!(i32, u32, u64, u128
);
4829 try_from_lower_bounded
!(i64, u64, u128
);
4830 try_from_lower_bounded
!(i128
, u128
);
4831 try_from_both_bounded
!(i16, u8);
4832 try_from_both_bounded
!(i32, u16, u8);
4833 try_from_both_bounded
!(i64, u32, u16, u8);
4834 try_from_both_bounded
!(i128
, u64, u32, u16, u8);
4837 try_from_upper_bounded
!(usize, isize);
4838 try_from_lower_bounded
!(isize, usize);
4840 #[cfg(target_pointer_width = "16")]
4841 mod ptr_try_from_impls
{
4842 use super::TryFromIntError
;
4843 use crate::convert
::TryFrom
;
4845 try_from_upper_bounded
!(usize, u8);
4846 try_from_unbounded
!(usize, u16, u32, u64, u128
);
4847 try_from_upper_bounded
!(usize, i8, i16);
4848 try_from_unbounded
!(usize, i32, i64, i128
);
4850 try_from_both_bounded
!(isize, u8);
4851 try_from_lower_bounded
!(isize, u16, u32, u64, u128
);
4852 try_from_both_bounded
!(isize, i8);
4853 try_from_unbounded
!(isize, i16, i32, i64, i128
);
4855 rev
!(try_from_upper_bounded
, usize, u32, u64, u128
);
4856 rev
!(try_from_lower_bounded
, usize, i8, i16);
4857 rev
!(try_from_both_bounded
, usize, i32, i64, i128
);
4859 rev
!(try_from_upper_bounded
, isize, u16, u32, u64, u128
);
4860 rev
!(try_from_both_bounded
, isize, i32, i64, i128
);
4863 #[cfg(target_pointer_width = "32")]
4864 mod ptr_try_from_impls
{
4865 use super::TryFromIntError
;
4866 use crate::convert
::TryFrom
;
4868 try_from_upper_bounded
!(usize, u8, u16);
4869 try_from_unbounded
!(usize, u32, u64, u128
);
4870 try_from_upper_bounded
!(usize, i8, i16, i32);
4871 try_from_unbounded
!(usize, i64, i128
);
4873 try_from_both_bounded
!(isize, u8, u16);
4874 try_from_lower_bounded
!(isize, u32, u64, u128
);
4875 try_from_both_bounded
!(isize, i8, i16);
4876 try_from_unbounded
!(isize, i32, i64, i128
);
4878 rev
!(try_from_unbounded
, usize, u32);
4879 rev
!(try_from_upper_bounded
, usize, u64, u128
);
4880 rev
!(try_from_lower_bounded
, usize, i8, i16, i32);
4881 rev
!(try_from_both_bounded
, usize, i64, i128
);
4883 rev
!(try_from_unbounded
, isize, u16);
4884 rev
!(try_from_upper_bounded
, isize, u32, u64, u128
);
4885 rev
!(try_from_unbounded
, isize, i32);
4886 rev
!(try_from_both_bounded
, isize, i64, i128
);
4889 #[cfg(target_pointer_width = "64")]
4890 mod ptr_try_from_impls
{
4891 use super::TryFromIntError
;
4892 use crate::convert
::TryFrom
;
4894 try_from_upper_bounded
!(usize, u8, u16, u32);
4895 try_from_unbounded
!(usize, u64, u128
);
4896 try_from_upper_bounded
!(usize, i8, i16, i32, i64);
4897 try_from_unbounded
!(usize, i128
);
4899 try_from_both_bounded
!(isize, u8, u16, u32);
4900 try_from_lower_bounded
!(isize, u64, u128
);
4901 try_from_both_bounded
!(isize, i8, i16, i32);
4902 try_from_unbounded
!(isize, i64, i128
);
4904 rev
!(try_from_unbounded
, usize, u32, u64);
4905 rev
!(try_from_upper_bounded
, usize, u128
);
4906 rev
!(try_from_lower_bounded
, usize, i8, i16, i32, i64);
4907 rev
!(try_from_both_bounded
, usize, i128
);
4909 rev
!(try_from_unbounded
, isize, u16, u32);
4910 rev
!(try_from_upper_bounded
, isize, u64, u128
);
4911 rev
!(try_from_unbounded
, isize, i32, i64);
4912 rev
!(try_from_both_bounded
, isize, i128
);
4916 trait FromStrRadixHelper
: PartialOrd
+ Copy
{
4917 fn min_value() -> Self;
4918 fn max_value() -> Self;
4919 fn from_u32(u
: u32) -> Self;
4920 fn checked_mul(&self, other
: u32) -> Option
<Self>;
4921 fn checked_sub(&self, other
: u32) -> Option
<Self>;
4922 fn checked_add(&self, other
: u32) -> Option
<Self>;
4926 ($
($t
:ty
)*) => ($
(impl FromStrRadixHelper
for $t
{
4928 fn min_value() -> Self { Self::min_value() }
4930 fn max_value() -> Self { Self::max_value() }
4932 fn from_u32(u
: u32) -> Self { u as Self }
4934 fn checked_mul(&self, other
: u32) -> Option
<Self> {
4935 Self::checked_mul(*self, other
as Self)
4938 fn checked_sub(&self, other
: u32) -> Option
<Self> {
4939 Self::checked_sub(*self, other
as Self)
4942 fn checked_add(&self, other
: u32) -> Option
<Self> {
4943 Self::checked_add(*self, other
as Self)
4947 doit
! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
4949 fn from_str_radix
<T
: FromStrRadixHelper
>(src
: &str, radix
: u32) -> Result
<T
, ParseIntError
> {
4950 use self::IntErrorKind
::*;
4951 use self::ParseIntError
as PIE
;
4953 assert
!(radix
>= 2 && radix
<= 36,
4954 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
4958 return Err(PIE { kind: Empty }
);
4961 let is_signed_ty
= T
::from_u32(0) > T
::min_value();
4963 // all valid digits are ascii, so we will just iterate over the utf8 bytes
4964 // and cast them to chars. .to_digit() will safely return None for anything
4965 // other than a valid ascii digit for the given radix, including the first-byte
4966 // of multi-byte sequences
4967 let src
= src
.as_bytes();
4969 let (is_positive
, digits
) = match src
[0] {
4970 b'
+'
=> (true, &src
[1..]),
4971 b'
-'
if is_signed_ty
=> (false, &src
[1..]),
4975 if digits
.is_empty() {
4976 return Err(PIE { kind: Empty }
);
4979 let mut result
= T
::from_u32(0);
4981 // The number is positive
4983 let x
= match (c
as char).to_digit(radix
) {
4985 None
=> return Err(PIE { kind: InvalidDigit }
),
4987 result
= match result
.checked_mul(radix
) {
4988 Some(result
) => result
,
4989 None
=> return Err(PIE { kind: Overflow }
),
4991 result
= match result
.checked_add(x
) {
4992 Some(result
) => result
,
4993 None
=> return Err(PIE { kind: Overflow }
),
4997 // The number is negative
4999 let x
= match (c
as char).to_digit(radix
) {
5001 None
=> return Err(PIE { kind: InvalidDigit }
),
5003 result
= match result
.checked_mul(radix
) {
5004 Some(result
) => result
,
5005 None
=> return Err(PIE { kind: Underflow }
),
5007 result
= match result
.checked_sub(x
) {
5008 Some(result
) => result
,
5009 None
=> return Err(PIE { kind: Underflow }
),
5016 /// An error which can be returned when parsing an integer.
5018 /// This error is used as the error type for the `from_str_radix()` functions
5019 /// on the primitive integer types, such as [`i8::from_str_radix`].
5021 /// # Potential causes
5023 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
5024 /// in the string e.g., when it is obtained from the standard input.
5025 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
5027 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
5028 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
5029 #[derive(Debug, Clone, PartialEq, Eq)]
5030 #[stable(feature = "rust1", since = "1.0.0")]
5031 pub struct ParseIntError
{
5035 /// Enum to store the various types of errors that can cause parsing an integer to fail.
5036 #[unstable(feature = "int_error_matching",
5037 reason
= "it can be useful to match errors when making error messages \
5038 for integer parsing",
5040 #[derive(Debug, Clone, PartialEq, Eq)]
5042 pub enum IntErrorKind
{
5043 /// Value being parsed is empty.
5045 /// Among other causes, this variant will be constructed when parsing an empty string.
5047 /// Contains an invalid digit.
5049 /// Among other causes, this variant will be constructed when parsing a string that
5050 /// contains a letter.
5052 /// Integer is too large to store in target integer type.
5054 /// Integer is too small to store in target integer type.
5058 /// This variant will be emitted when the parsing string has a value of zero, which
5059 /// would be illegal for non-zero types.
5063 impl ParseIntError
{
5064 /// Outputs the detailed cause of parsing an integer failing.
5065 #[unstable(feature = "int_error_matching",
5066 reason
= "it can be useful to match errors when making error messages \
5067 for integer parsing",
5069 pub fn kind(&self) -> &IntErrorKind
{
5072 #[unstable(feature = "int_error_internals",
5073 reason
= "available through Error trait and this method should \
5074 not be exposed publicly",
5077 pub fn __description(&self) -> &str {
5079 IntErrorKind
::Empty
=> "cannot parse integer from empty string",
5080 IntErrorKind
::InvalidDigit
=> "invalid digit found in string",
5081 IntErrorKind
::Overflow
=> "number too large to fit in target type",
5082 IntErrorKind
::Underflow
=> "number too small to fit in target type",
5083 IntErrorKind
::Zero
=> "number would be zero for non-zero type",
5088 #[stable(feature = "rust1", since = "1.0.0")]
5089 impl fmt
::Display
for ParseIntError
{
5090 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
5091 self.__description().fmt(f
)
5095 #[stable(feature = "rust1", since = "1.0.0")]
5096 pub use crate::num
::dec2flt
::ParseFloatError
;
5098 // Conversion traits for primitive integer and float types
5099 // Conversions T -> T are covered by a blanket impl and therefore excluded
5100 // Some conversions from and to usize/isize are not implemented due to portability concerns
5101 macro_rules
! impl_from
{
5102 ($Small
: ty
, $Large
: ty
, #[$attr:meta], $doc: expr) => {
5105 impl From
<$Small
> for $Large
{
5107 fn from(small
: $Small
) -> $Large
{
5112 ($Small
: ty
, $Large
: ty
, #[$attr:meta]) => {
5116 concat
!("Converts `",
5124 macro_rules
! impl_from_bool
{
5125 ($target
: ty
, #[$attr:meta]) => {
5126 impl_from
!(bool
, $target
, #[$attr], concat!("Converts a `bool` to a `",
5127 stringify
!($target
), "`. The resulting value is `0` for `false` and `1` for `true`
5133 assert_eq!(", stringify
!($target
), "::from(true), 1);
5134 assert_eq!(", stringify
!($target
), "::from(false), 0);
5140 impl_from_bool
! { u8, #[stable(feature = "from_bool", since = "1.28.0")] }
5141 impl_from_bool
! { u16, #[stable(feature = "from_bool", since = "1.28.0")] }
5142 impl_from_bool
! { u32, #[stable(feature = "from_bool", since = "1.28.0")] }
5143 impl_from_bool
! { u64, #[stable(feature = "from_bool", since = "1.28.0")] }
5144 impl_from_bool
! { u128, #[stable(feature = "from_bool", since = "1.28.0")] }
5145 impl_from_bool
! { usize, #[stable(feature = "from_bool", since = "1.28.0")] }
5146 impl_from_bool
! { i8, #[stable(feature = "from_bool", since = "1.28.0")] }
5147 impl_from_bool
! { i16, #[stable(feature = "from_bool", since = "1.28.0")] }
5148 impl_from_bool
! { i32, #[stable(feature = "from_bool", since = "1.28.0")] }
5149 impl_from_bool
! { i64, #[stable(feature = "from_bool", since = "1.28.0")] }
5150 impl_from_bool
! { i128, #[stable(feature = "from_bool", since = "1.28.0")] }
5151 impl_from_bool
! { isize, #[stable(feature = "from_bool", since = "1.28.0")] }
5153 // Unsigned -> Unsigned
5154 impl_from
! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5155 impl_from
! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5156 impl_from
! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5157 impl_from
! { u8, u128, #[stable(feature = "i128", since = "1.26.0")] }
5158 impl_from
! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5159 impl_from
! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5160 impl_from
! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5161 impl_from
! { u16, u128, #[stable(feature = "i128", since = "1.26.0")] }
5162 impl_from
! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5163 impl_from
! { u32, u128, #[stable(feature = "i128", since = "1.26.0")] }
5164 impl_from
! { u64, u128, #[stable(feature = "i128", since = "1.26.0")] }
5167 impl_from
! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5168 impl_from
! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5169 impl_from
! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5170 impl_from
! { i8, i128, #[stable(feature = "i128", since = "1.26.0")] }
5171 impl_from
! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5172 impl_from
! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5173 impl_from
! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5174 impl_from
! { i16, i128, #[stable(feature = "i128", since = "1.26.0")] }
5175 impl_from
! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5176 impl_from
! { i32, i128, #[stable(feature = "i128", since = "1.26.0")] }
5177 impl_from
! { i64, i128, #[stable(feature = "i128", since = "1.26.0")] }
5179 // Unsigned -> Signed
5180 impl_from
! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5181 impl_from
! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5182 impl_from
! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5183 impl_from
! { u8, i128, #[stable(feature = "i128", since = "1.26.0")] }
5184 impl_from
! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5185 impl_from
! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5186 impl_from
! { u16, i128, #[stable(feature = "i128", since = "1.26.0")] }
5187 impl_from
! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5188 impl_from
! { u32, i128, #[stable(feature = "i128", since = "1.26.0")] }
5189 impl_from
! { u64, i128, #[stable(feature = "i128", since = "1.26.0")] }
5191 // The C99 standard defines bounds on INTPTR_MIN, INTPTR_MAX, and UINTPTR_MAX
5192 // which imply that pointer-sized integers must be at least 16 bits:
5193 // https://port70.net/~nsz/c/c99/n1256.html#7.18.2.4
5194 impl_from
! { u16, usize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
5195 impl_from
! { u8, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
5196 impl_from
! { i16, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
5198 // RISC-V defines the possibility of a 128-bit address space (RV128).
5200 // CHERI proposes 256-bit “capabilities”. Unclear if this would be relevant to usize/isize.
5201 // https://www.cl.cam.ac.uk/research/security/ctsrd/pdfs/20171017a-cheri-poster.pdf
5202 // http://www.csl.sri.com/users/neumann/2012resolve-cheri.pdf
5205 // Note: integers can only be represented with full precision in a float if
5206 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
5207 // Lossy float conversions are not implemented at this time.
5210 impl_from
! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5211 impl_from
! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5212 impl_from
! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5213 impl_from
! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5214 impl_from
! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5216 // Unsigned -> Float
5217 impl_from
! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5218 impl_from
! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5219 impl_from
! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5220 impl_from
! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5221 impl_from
! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5224 impl_from
! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }