1 //! Numeric traits and functions for the built-in numeric types.
3 #![stable(feature = "rust1", since = "1.0.0")]
12 macro_rules! impl_nonzero_fmt {
13 ( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
16 impl fmt::$Trait for $Ty {
18 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
26 macro_rules! doc_comment {
27 ($x:expr, $($tt:tt)*) => {
33 macro_rules! nonzero_integers {
34 ( $( #[$stability: meta] $Ty: ident($Int: ty); )+ ) => {
37 concat!("An integer that is known not to equal zero.
39 This enables some memory layout optimization.
40 For example, `Option<", stringify!($Ty), ">` is the same size as `", stringify!($Int), "`:
43 use std::mem::size_of;
44 assert_eq!(size_of::<Option<core::num::", stringify!($Ty), ">>(), size_of::<", stringify!($Int),
48 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
50 #[rustc_layout_scalar_valid_range_start(1)]
55 /// Create a non-zero without checking the value.
59 /// The value must not be zero.
62 pub const unsafe fn new_unchecked(n: $Int) -> Self {
66 /// Create a non-zero if the given value is not zero.
69 pub fn new(n: $Int) -> Option<Self> {
71 Some(unsafe { $Ty(n) })
77 /// Returns the value as a primitive type.
80 pub const fn get(self) -> $Int {
86 #[stable(feature = "from_nonzero", since = "1.31.0")]
87 impl From<$Ty> for $Int {
88 fn from(nonzero: $Ty) -> Self {
94 #[$stability] (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
101 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU8(u8);
102 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU16(u16);
103 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU32(u32);
104 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU64(u64);
105 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroU128(u128);
106 #[stable(feature = "nonzero", since = "1.28.0")] NonZeroUsize(usize);
107 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI8(i8);
108 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI16(i16);
109 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI32(i32);
110 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI64(i64);
111 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI128(i128);
112 #[stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroIsize(isize);
115 /// Provides intentionally-wrapped arithmetic on `T`.
117 /// Operations like `+` on `u32` values is intended to never overflow,
118 /// and in some debug configurations overflow is detected and results
119 /// in a panic. While most arithmetic falls into this category, some
120 /// code explicitly expects and relies upon modular arithmetic (e.g.,
123 /// Wrapping arithmetic can be achieved either through methods like
124 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
125 /// all standard arithmetic operations on the underlying value are
126 /// intended to have wrapping semantics.
128 /// The underlying value can be retrieved through the `.0` index of the
129 /// `Wrapping` tuple.
134 /// use std::num::Wrapping;
136 /// let zero = Wrapping(0u32);
137 /// let one = Wrapping(1u32);
139 /// assert_eq!(std::u32::MAX, (zero - one).0);
141 #[stable(feature = "rust1", since = "1.0.0")]
142 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
144 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")]
147 #[stable(feature = "rust1", since = "1.0.0")]
148 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
149 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
154 #[stable(feature = "wrapping_display", since = "1.10.0")]
155 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
156 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
161 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
162 impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
163 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
168 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
169 impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
170 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
175 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
176 impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
177 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
182 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
183 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
184 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
189 // All these modules are technically private and only exposed for coretests:
197 // `Int` + `SignedInt` implemented for signed integers
198 macro_rules! int_impl {
199 ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $Min:expr, $Max:expr, $Feature:expr,
200 $EndFeature:expr, $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
201 $reversed:expr, $le_bytes:expr, $be_bytes:expr) => {
203 concat!("Returns the smallest value that can be represented by this integer type.
210 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), ", stringify!($Min), ");",
213 #[stable(feature = "rust1", since = "1.0.0")]
216 pub const fn min_value() -> Self {
217 !0 ^ ((!0 as $UnsignedT) >> 1) as Self
222 concat!("Returns the largest value that can be represented by this integer type.
229 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ", stringify!($Max), ");",
232 #[stable(feature = "rust1", since = "1.0.0")]
235 pub const fn max_value() -> Self {
241 concat!("Converts a string slice in a given base to an integer.
243 The string is expected to be an optional `+` or `-` sign followed by digits.
244 Leading and trailing whitespace represent an error. Digits are a subset of these characters,
245 depending on `radix`:
253 This function panics if `radix` is not in the range from 2 to 36.
260 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
263 #[stable(feature = "rust1", since = "1.0.0")]
264 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
265 from_str_radix(src, radix)
270 concat!("Returns the number of ones in the binary representation of `self`.
277 ", $Feature, "let n = 0b100_0000", stringify!($SelfT), ";
279 assert_eq!(n.count_ones(), 1);",
283 #[stable(feature = "rust1", since = "1.0.0")]
284 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_ops"))]
286 pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
290 concat!("Returns the number of zeros in the binary representation of `self`.
297 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 1);", $EndFeature, "
299 #[stable(feature = "rust1", since = "1.0.0")]
300 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_ops"))]
302 pub const fn count_zeros(self) -> u32 {
308 concat!("Returns the number of leading zeros in the binary representation of `self`.
315 ", $Feature, "let n = -1", stringify!($SelfT), ";
317 assert_eq!(n.leading_zeros(), 0);",
320 #[stable(feature = "rust1", since = "1.0.0")]
321 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_ops"))]
323 pub const fn leading_zeros(self) -> u32 {
324 (self as $UnsignedT).leading_zeros()
329 concat!("Returns the number of trailing zeros in the binary representation of `self`.
336 ", $Feature, "let n = -4", stringify!($SelfT), ";
338 assert_eq!(n.trailing_zeros(), 2);",
341 #[stable(feature = "rust1", since = "1.0.0")]
342 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_ops"))]
344 pub const fn trailing_zeros(self) -> u32 {
345 (self as $UnsignedT).trailing_zeros()
350 concat!("Shifts the bits to the left by a specified amount, `n`,
351 wrapping the truncated bits to the end of the resulting integer.
353 Please note this isn't the same operation as `<<`!
360 let n = ", $rot_op, stringify!($SelfT), ";
361 let m = ", $rot_result, ";
363 assert_eq!(n.rotate_left(", $rot, "), m);
365 #[stable(feature = "rust1", since = "1.0.0")]
366 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_rotate"))]
368 pub const fn rotate_left(self, n: u32) -> Self {
369 (self as $UnsignedT).rotate_left(n) as Self
374 concat!("Shifts the bits to the right by a specified amount, `n`,
375 wrapping the truncated bits to the beginning of the resulting
378 Please note this isn't the same operation as `>>`!
385 let n = ", $rot_result, stringify!($SelfT), ";
386 let m = ", $rot_op, ";
388 assert_eq!(n.rotate_right(", $rot, "), m);
390 #[stable(feature = "rust1", since = "1.0.0")]
391 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_rotate"))]
393 pub const fn rotate_right(self, n: u32) -> Self {
394 (self as $UnsignedT).rotate_right(n) as Self
399 concat!("Reverses the byte order of the integer.
406 let n = ", $swap_op, stringify!($SelfT), ";
408 let m = n.swap_bytes();
410 assert_eq!(m, ", $swapped, ");
412 #[stable(feature = "rust1", since = "1.0.0")]
413 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_ops"))]
415 pub const fn swap_bytes(self) -> Self {
416 (self as $UnsignedT).swap_bytes() as Self
421 concat!("Reverses the bit pattern of the integer.
428 #![feature(reverse_bits)]
430 let n = ", $swap_op, stringify!($SelfT), ";
431 let m = n.reverse_bits();
433 assert_eq!(m, ", $reversed, ");
435 #[unstable(feature = "reverse_bits", issue = "48763")]
436 #[rustc_const_unstable(feature = "const_int_conversion")]
438 pub const fn reverse_bits(self) -> Self {
439 (self as $UnsignedT).reverse_bits() as Self
444 concat!("Converts an integer from big endian to the target's endianness.
446 On big endian this is a no-op. On little endian the bytes are swapped.
453 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
455 if cfg!(target_endian = \"big\") {
456 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
458 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
462 #[stable(feature = "rust1", since = "1.0.0")]
463 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_ops"))]
465 pub const fn from_be(x: Self) -> Self {
466 #[cfg(target_endian = "big")]
470 #[cfg(not(target_endian = "big"))]
478 concat!("Converts an integer from little endian to the target's endianness.
480 On little endian this is a no-op. On big endian the bytes are swapped.
487 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
489 if cfg!(target_endian = \"little\") {
490 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
492 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
496 #[stable(feature = "rust1", since = "1.0.0")]
497 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_ops"))]
499 pub const fn from_le(x: Self) -> Self {
500 #[cfg(target_endian = "little")]
504 #[cfg(not(target_endian = "little"))]
512 concat!("Converts `self` to big endian from the target's endianness.
514 On big endian this is a no-op. On little endian the bytes are swapped.
521 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
523 if cfg!(target_endian = \"big\") {
524 assert_eq!(n.to_be(), n)
526 assert_eq!(n.to_be(), n.swap_bytes())
530 #[stable(feature = "rust1", since = "1.0.0")]
531 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_ops"))]
533 pub const fn to_be(self) -> Self { // or not to be?
534 #[cfg(target_endian = "big")]
538 #[cfg(not(target_endian = "big"))]
546 concat!("Converts `self` to little endian from the target's endianness.
548 On little endian this is a no-op. On big endian the bytes are swapped.
555 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
557 if cfg!(target_endian = \"little\") {
558 assert_eq!(n.to_le(), n)
560 assert_eq!(n.to_le(), n.swap_bytes())
564 #[stable(feature = "rust1", since = "1.0.0")]
565 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_ops"))]
567 pub const fn to_le(self) -> Self {
568 #[cfg(target_endian = "little")]
572 #[cfg(not(target_endian = "little"))]
580 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
581 if overflow occurred.
588 ", $Feature, "assert_eq!((", stringify!($SelfT),
589 "::max_value() - 2).checked_add(1), Some(", stringify!($SelfT), "::max_value() - 1));
590 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);",
593 #[stable(feature = "rust1", since = "1.0.0")]
595 pub fn checked_add(self, rhs: Self) -> Option<Self> {
596 let (a, b) = self.overflowing_add(rhs);
597 if b {None} else {Some(a)}
602 concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
610 ", $Feature, "assert_eq!((", stringify!($SelfT),
611 "::min_value() + 2).checked_sub(1), Some(", stringify!($SelfT), "::min_value() + 1));
612 assert_eq!((", stringify!($SelfT), "::min_value() + 2).checked_sub(3), None);",
615 #[stable(feature = "rust1", since = "1.0.0")]
617 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
618 let (a, b) = self.overflowing_sub(rhs);
619 if b {None} else {Some(a)}
624 concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
632 ", $Feature, "assert_eq!(", stringify!($SelfT),
633 "::max_value().checked_mul(1), Some(", stringify!($SelfT), "::max_value()));
634 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);",
637 #[stable(feature = "rust1", since = "1.0.0")]
639 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
640 let (a, b) = self.overflowing_mul(rhs);
641 if b {None} else {Some(a)}
646 concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
647 or the division results in overflow.
654 ", $Feature, "assert_eq!((", stringify!($SelfT),
655 "::min_value() + 1).checked_div(-1), Some(", stringify!($Max), "));
656 assert_eq!(", stringify!($SelfT), "::min_value().checked_div(-1), None);
657 assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
660 #[stable(feature = "rust1", since = "1.0.0")]
662 pub fn checked_div(self, rhs: Self) -> Option<Self> {
663 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
666 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
672 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`,
673 returning `None` if `rhs == 0` or the division results in overflow.
680 #![feature(euclidean_division)]
681 assert_eq!((", stringify!($SelfT),
682 "::min_value() + 1).checked_div_euclid(-1), Some(", stringify!($Max), "));
683 assert_eq!(", stringify!($SelfT), "::min_value().checked_div_euclid(-1), None);
684 assert_eq!((1", stringify!($SelfT), ").checked_div_euclid(0), None);
686 #[unstable(feature = "euclidean_division", issue = "49048")]
688 pub fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
689 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
692 Some(self.div_euclid(rhs))
698 concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
699 `rhs == 0` or the division results in overflow.
706 ", $Feature, "use std::", stringify!($SelfT), ";
708 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
709 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
710 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
713 #[stable(feature = "wrapping", since = "1.7.0")]
715 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
716 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
719 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
725 concat!("Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`
726 if `rhs == 0` or the division results in overflow.
733 #![feature(euclidean_division)]
734 use std::", stringify!($SelfT), ";
736 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
737 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
738 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem_euclid(-1), None);
740 #[unstable(feature = "euclidean_division", issue = "49048")]
742 pub fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
743 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
746 Some(self.rem_euclid(rhs))
752 concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
759 ", $Feature, "use std::", stringify!($SelfT), ";
761 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
762 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
765 #[stable(feature = "wrapping", since = "1.7.0")]
767 pub fn checked_neg(self) -> Option<Self> {
768 let (a, b) = self.overflowing_neg();
769 if b {None} else {Some(a)}
774 concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
775 than or equal to the number of bits in `self`.
782 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
783 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
786 #[stable(feature = "wrapping", since = "1.7.0")]
788 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
789 let (a, b) = self.overflowing_shl(rhs);
790 if b {None} else {Some(a)}
795 concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
796 larger than or equal to the number of bits in `self`.
803 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
804 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
807 #[stable(feature = "wrapping", since = "1.7.0")]
809 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
810 let (a, b) = self.overflowing_shr(rhs);
811 if b {None} else {Some(a)}
816 concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
824 ", $Feature, "use std::", stringify!($SelfT), ";
826 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
827 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
830 #[stable(feature = "no_panic_abs", since = "1.13.0")]
832 pub fn checked_abs(self) -> Option<Self> {
833 if self.is_negative() {
842 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
850 #![feature(no_panic_pow)]
851 ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
852 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);",
856 #[unstable(feature = "no_panic_pow", issue = "48320")]
858 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
860 let mut acc: Self = 1;
864 acc = acc.checked_mul(base)?;
867 base = base.checked_mul(base)?;
870 // Deal with the final bit of the exponent separately, since
871 // squaring the base afterwards is not necessary and may cause a
872 // needless overflow.
874 acc = acc.checked_mul(base)?;
882 concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
883 bounds instead of overflowing.
890 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
891 assert_eq!(", stringify!($SelfT), "::max_value().saturating_add(100), ", stringify!($SelfT),
895 #[stable(feature = "rust1", since = "1.0.0")]
897 pub fn saturating_add(self, rhs: Self) -> Self {
898 match self.checked_add(rhs) {
900 None if rhs >= 0 => Self::max_value(),
901 None => Self::min_value(),
907 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
908 numeric bounds instead of overflowing.
915 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
916 assert_eq!(", stringify!($SelfT), "::min_value().saturating_sub(100), ", stringify!($SelfT),
920 #[stable(feature = "rust1", since = "1.0.0")]
922 pub fn saturating_sub(self, rhs: Self) -> Self {
923 match self.checked_sub(rhs) {
925 None if rhs >= 0 => Self::min_value(),
926 None => Self::max_value(),
932 concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
933 numeric bounds instead of overflowing.
940 ", $Feature, "use std::", stringify!($SelfT), ";
942 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
943 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
944 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
947 #[stable(feature = "wrapping", since = "1.7.0")]
949 pub fn saturating_mul(self, rhs: Self) -> Self {
950 self.checked_mul(rhs).unwrap_or_else(|| {
951 if (self < 0 && rhs < 0) || (self > 0 && rhs > 0) {
961 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
962 saturating at the numeric bounds instead of overflowing.
969 #![feature(no_panic_pow)]
970 ", $Feature, "use std::", stringify!($SelfT), ";
972 assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
973 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
974 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
977 #[unstable(feature = "no_panic_pow", issue = "48320")]
979 pub fn saturating_pow(self, exp: u32) -> Self {
980 match self.checked_pow(exp) {
982 None if self < 0 && exp % 2 == 1 => Self::min_value(),
983 None => Self::max_value(),
989 concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
990 boundary of the type.
997 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
998 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_add(2), ", stringify!($SelfT),
999 "::min_value() + 1);",
1002 #[stable(feature = "rust1", since = "1.0.0")]
1003 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_wrapping"))]
1005 pub const fn wrapping_add(self, rhs: Self) -> Self {
1008 intrinsics::overflowing_add(self, rhs)
1011 intrinsics::overflowing_add(self, rhs)
1016 concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1017 boundary of the type.
1024 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
1025 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::max_value()), ",
1026 stringify!($SelfT), "::max_value());",
1029 #[stable(feature = "rust1", since = "1.0.0")]
1030 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_wrapping"))]
1032 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1035 intrinsics::overflowing_sub(self, rhs)
1038 intrinsics::overflowing_sub(self, rhs)
1043 concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1044 the boundary of the type.
1051 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
1052 assert_eq!(11i8.wrapping_mul(12), -124);",
1055 #[stable(feature = "rust1", since = "1.0.0")]
1056 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_wrapping"))]
1058 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1061 intrinsics::overflowing_mul(self, rhs)
1064 intrinsics::overflowing_mul(self, rhs)
1069 concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1070 boundary of the type.
1072 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1073 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1074 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1078 This function will panic if `rhs` is 0.
1085 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
1086 assert_eq!((-128i8).wrapping_div(-1), -128);",
1089 #[stable(feature = "num_wrapping", since = "1.2.0")]
1091 pub fn wrapping_div(self, rhs: Self) -> Self {
1092 self.overflowing_div(rhs).0
1097 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
1098 wrapping around at the boundary of the type.
1100 Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1101 for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1102 type. In this case, this method returns `MIN` itself.
1106 This function will panic if `rhs` is 0.
1113 #![feature(euclidean_division)]
1114 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
1115 assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
1117 #[unstable(feature = "euclidean_division", issue = "49048")]
1119 pub fn wrapping_div_euclid(self, rhs: Self) -> Self {
1120 self.overflowing_div_euclid(rhs).0
1125 concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1126 boundary of the type.
1128 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1129 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1130 this function returns `0`.
1134 This function will panic if `rhs` is 0.
1141 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
1142 assert_eq!((-128i8).wrapping_rem(-1), 0);",
1145 #[stable(feature = "num_wrapping", since = "1.2.0")]
1147 pub fn wrapping_rem(self, rhs: Self) -> Self {
1148 self.overflowing_rem(rhs).0
1153 concat!("Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
1154 at the boundary of the type.
1156 Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1157 for the type). In this case, this method returns 0.
1161 This function will panic if `rhs` is 0.
1168 #![feature(euclidean_division)]
1169 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
1170 assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
1172 #[unstable(feature = "euclidean_division", issue = "49048")]
1174 pub fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1175 self.overflowing_rem_euclid(rhs).0
1180 concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1183 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1184 is the negative minimal value for the type); this is a positive value that is too large to represent
1185 in the type. In such a case, this function returns `MIN` itself.
1192 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
1193 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_neg(), ", stringify!($SelfT),
1197 #[stable(feature = "num_wrapping", since = "1.2.0")]
1199 pub fn wrapping_neg(self) -> Self {
1200 self.overflowing_neg().0
1205 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1206 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1208 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1209 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1210 The primitive integer types all implement a `rotate_left` function, which may be what you want
1218 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
1219 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
1222 #[stable(feature = "num_wrapping", since = "1.2.0")]
1223 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_wrapping"))]
1225 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1227 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1233 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1234 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1236 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1237 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1238 end. The primitive integer types all implement a `rotate_right` function, which may be what you want
1246 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
1247 assert_eq!((-128i16).wrapping_shr(64), -128);",
1250 #[stable(feature = "num_wrapping", since = "1.2.0")]
1251 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_wrapping"))]
1253 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1255 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1261 concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1262 the boundary of the type.
1264 The only case where such wrapping can occur is when one takes the absolute value of the negative
1265 minimal value for the type this is a positive value that is too large to represent in the type. In
1266 such a case, this function returns `MIN` itself.
1273 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
1274 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
1275 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_abs(), ", stringify!($SelfT),
1277 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1280 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1282 pub fn wrapping_abs(self) -> Self {
1283 if self.is_negative() {
1292 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1293 wrapping around at the boundary of the type.
1300 #![feature(no_panic_pow)]
1301 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);
1302 assert_eq!(3i8.wrapping_pow(5), -13);
1303 assert_eq!(3i8.wrapping_pow(6), -39);",
1306 #[unstable(feature = "no_panic_pow", issue = "48320")]
1308 pub fn wrapping_pow(self, mut exp: u32) -> Self {
1309 let mut base = self;
1310 let mut acc: Self = 1;
1314 acc = acc.wrapping_mul(base);
1317 base = base.wrapping_mul(base);
1320 // Deal with the final bit of the exponent separately, since
1321 // squaring the base afterwards is not necessary and may cause a
1322 // needless overflow.
1324 acc = acc.wrapping_mul(base);
1332 concat!("Calculates `self` + `rhs`
1334 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1335 occur. If an overflow would have occurred then the wrapped value is returned.
1342 ", $Feature, "use std::", stringify!($SelfT), ";
1344 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1345 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
1346 "::MIN, true));", $EndFeature, "
1348 #[stable(feature = "wrapping", since = "1.7.0")]
1349 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_overflowing"))]
1351 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1353 let (a, b) = unsafe {
1354 intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT)
1357 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1363 concat!("Calculates `self` - `rhs`
1365 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1366 would occur. If an overflow would have occurred then the wrapped value is returned.
1373 ", $Feature, "use std::", stringify!($SelfT), ";
1375 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
1376 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
1377 "::MAX, true));", $EndFeature, "
1379 #[stable(feature = "wrapping", since = "1.7.0")]
1380 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_overflowing"))]
1382 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1384 let (a, b) = unsafe {
1385 intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT)
1388 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1394 concat!("Calculates the multiplication of `self` and `rhs`.
1396 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1397 would occur. If an overflow would have occurred then the wrapped value is returned.
1404 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1405 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1408 #[stable(feature = "wrapping", since = "1.7.0")]
1409 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_overflowing"))]
1411 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1413 let (a, b) = unsafe {
1414 intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT)
1417 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1423 concat!("Calculates the divisor when `self` is divided by `rhs`.
1425 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1426 occur. If an overflow would occur then self is returned.
1430 This function will panic if `rhs` is 0.
1437 ", $Feature, "use std::", stringify!($SelfT), ";
1439 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1440 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1445 #[stable(feature = "wrapping", since = "1.7.0")]
1446 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1447 if self == Self::min_value() && rhs == -1 {
1456 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1458 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1459 occur. If an overflow would occur then `self` is returned.
1463 This function will panic if `rhs` is 0.
1470 #![feature(euclidean_division)]
1471 use std::", stringify!($SelfT), ";
1473 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
1474 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euclid(-1), (", stringify!($SelfT),
1478 #[unstable(feature = "euclidean_division", issue = "49048")]
1479 pub fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1480 if self == Self::min_value() && rhs == -1 {
1483 (self.div_euclid(rhs), false)
1489 concat!("Calculates the remainder when `self` is divided by `rhs`.
1491 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1492 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1496 This function will panic if `rhs` is 0.
1503 ", $Feature, "use std::", stringify!($SelfT), ";
1505 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1506 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1510 #[stable(feature = "wrapping", since = "1.7.0")]
1511 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1512 if self == Self::min_value() && rhs == -1 {
1522 concat!("Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
1524 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1525 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1529 This function will panic if `rhs` is 0.
1536 #![feature(euclidean_division)]
1537 use std::", stringify!($SelfT), ";
1539 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
1540 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem_euclid(-1), (0, true));
1542 #[unstable(feature = "euclidean_division", issue = "49048")]
1544 pub fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1545 if self == Self::min_value() && rhs == -1 {
1548 (self.rem_euclid(rhs), false)
1555 concat!("Negates self, overflowing if this is equal to the minimum value.
1557 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1558 happened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the
1559 minimum value will be returned again and `true` will be returned for an overflow happening.
1566 ", $Feature, "use std::", stringify!($SelfT), ";
1568 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1569 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1570 "::MIN, true));", $EndFeature, "
1573 #[stable(feature = "wrapping", since = "1.7.0")]
1574 pub fn overflowing_neg(self) -> (Self, bool) {
1575 if self == Self::min_value() {
1576 (Self::min_value(), true)
1584 concat!("Shifts self left by `rhs` bits.
1586 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1587 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1588 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1595 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1596 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1599 #[stable(feature = "wrapping", since = "1.7.0")]
1600 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_overflowing"))]
1602 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1603 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1608 concat!("Shifts self right by `rhs` bits.
1610 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1611 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1612 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1619 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1620 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1623 #[stable(feature = "wrapping", since = "1.7.0")]
1624 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_overflowing"))]
1626 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1627 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1632 concat!("Computes the absolute value of `self`.
1634 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1635 happened. If self is the minimum value (e.g., ", stringify!($SelfT), "::MIN for values of type
1636 ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1637 for an overflow happening.
1644 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1645 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1646 assert_eq!((", stringify!($SelfT), "::min_value()).overflowing_abs(), (", stringify!($SelfT),
1647 "::min_value(), true));",
1650 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1652 pub fn overflowing_abs(self) -> (Self, bool) {
1653 if self.is_negative() {
1654 self.overflowing_neg()
1662 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1664 Returns a tuple of the exponentiation along with a bool indicating
1665 whether an overflow happened.
1672 #![feature(no_panic_pow)]
1673 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));
1674 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
1677 #[unstable(feature = "no_panic_pow", issue = "48320")]
1679 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1680 let mut base = self;
1681 let mut acc: Self = 1;
1682 let mut overflown = false;
1683 // Scratch space for storing results of overflowing_mul.
1688 r = acc.overflowing_mul(base);
1693 r = base.overflowing_mul(base);
1698 // Deal with the final bit of the exponent separately, since
1699 // squaring the base afterwards is not necessary and may cause a
1700 // needless overflow.
1702 r = acc.overflowing_mul(base);
1712 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1719 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
1721 assert_eq!(x.pow(5), 32);",
1724 #[stable(feature = "rust1", since = "1.0.0")]
1726 #[rustc_inherit_overflow_checks]
1727 pub fn pow(self, mut exp: u32) -> Self {
1728 let mut base = self;
1739 // Deal with the final bit of the exponent separately, since
1740 // squaring the base afterwards is not necessary and may cause a
1741 // needless overflow.
1751 concat!("Calculates the quotient of Euclidean division of `self` by `rhs`.
1753 This computes the integer `n` such that `self = n * rhs + self.rem_euclid(rhs)`,
1754 with `0 <= self.rem_euclid(rhs) < rhs`.
1756 In other words, the result is `self / rhs` rounded to the integer `n`
1757 such that `self >= n * rhs`.
1758 If `self > 0`, this is equal to round towards zero (the default in Rust);
1759 if `self < 0`, this is equal to round towards +/- infinity.
1763 This function will panic if `rhs` is 0.
1770 #![feature(euclidean_division)]
1771 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1774 assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
1775 assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
1776 assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
1777 assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
1779 #[unstable(feature = "euclidean_division", issue = "49048")]
1781 #[rustc_inherit_overflow_checks]
1782 pub fn div_euclid(self, rhs: Self) -> Self {
1785 return if rhs > 0 { q - 1 } else { q + 1 }
1793 concat!("Calculates the least nonnegative remainder of `self (mod rhs)`.
1795 This is done as if by the Euclidean division algorithm -- given
1796 `r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) + r`, and
1797 `0 <= r < abs(rhs)`.
1801 This function will panic if `rhs` is 0.
1808 #![feature(euclidean_division)]
1809 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1812 assert_eq!(a.rem_euclid(b), 3);
1813 assert_eq!((-a).rem_euclid(b), 1);
1814 assert_eq!(a.rem_euclid(-b), 3);
1815 assert_eq!((-a).rem_euclid(-b), 1);
1817 #[unstable(feature = "euclidean_division", issue = "49048")]
1819 #[rustc_inherit_overflow_checks]
1820 pub fn rem_euclid(self, rhs: Self) -> Self {
1835 concat!("Computes the absolute value of `self`.
1839 The absolute value of `", stringify!($SelfT), "::min_value()` cannot be represented as an
1840 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
1841 code in debug mode will trigger a panic on this case and optimized code will return `",
1842 stringify!($SelfT), "::min_value()` without a panic.
1849 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
1850 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
1853 #[stable(feature = "rust1", since = "1.0.0")]
1855 #[rustc_inherit_overflow_checks]
1856 pub fn abs(self) -> Self {
1857 if self.is_negative() {
1858 // Note that the #[inline] above means that the overflow
1859 // semantics of this negation depend on the crate we're being
1869 concat!("Returns a number representing sign of `self`.
1871 - `0` if the number is zero
1872 - `1` if the number is positive
1873 - `-1` if the number is negative
1880 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
1881 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
1882 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
1885 #[stable(feature = "rust1", since = "1.0.0")]
1887 pub fn signum(self) -> Self {
1897 concat!("Returns `true` if `self` is positive and `false` if the number is zero or
1905 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
1906 assert!(!(-10", stringify!($SelfT), ").is_positive());",
1909 #[stable(feature = "rust1", since = "1.0.0")]
1911 pub const fn is_positive(self) -> bool { self > 0 }
1915 concat!("Returns `true` if `self` is negative and `false` if the number is zero or
1923 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
1924 assert!(!10", stringify!($SelfT), ".is_negative());",
1927 #[stable(feature = "rust1", since = "1.0.0")]
1929 pub const fn is_negative(self) -> bool { self < 0 }
1933 concat!("Return the memory representation of this integer as a byte array in
1934 big-endian (network) byte order.
1939 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
1940 assert_eq!(bytes, ", $be_bytes, ");
1942 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
1943 #[rustc_const_unstable(feature = "const_int_conversion")]
1945 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
1946 self.to_be().to_ne_bytes()
1951 concat!("Return the memory representation of this integer as a byte array in
1952 little-endian byte order.
1957 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
1958 assert_eq!(bytes, ", $le_bytes, ");
1960 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
1961 #[rustc_const_unstable(feature = "const_int_conversion")]
1963 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
1964 self.to_le().to_ne_bytes()
1970 Return the memory representation of this integer as a byte array in
1973 As the target platform's native endianness is used, portable code
1974 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
1977 [`to_be_bytes`]: #method.to_be_bytes
1978 [`to_le_bytes`]: #method.to_le_bytes
1983 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
1984 assert_eq!(bytes, if cfg!(target_endian = \"big\") {
1990 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
1991 #[rustc_const_unstable(feature = "const_int_conversion")]
1993 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
1994 unsafe { mem::transmute(self) }
1999 concat!("Create an integer value from its representation as a byte array in
2005 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
2006 assert_eq!(value, ", $swap_op, ");
2009 When starting from a slice rather than an array, fallible conversion APIs can be used:
2012 #![feature(try_from)]
2013 use std::convert::TryInto;
2015 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2016 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2018 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
2021 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2022 #[rustc_const_unstable(feature = "const_int_conversion")]
2024 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2025 Self::from_be(Self::from_ne_bytes(bytes))
2031 Create an integer value from its representation as a byte array in
2037 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
2038 assert_eq!(value, ", $swap_op, ");
2041 When starting from a slice rather than an array, fallible conversion APIs can be used:
2044 #![feature(try_from)]
2045 use std::convert::TryInto;
2047 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2048 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2050 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
2053 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2054 #[rustc_const_unstable(feature = "const_int_conversion")]
2056 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2057 Self::from_le(Self::from_ne_bytes(bytes))
2062 concat!("Create an integer value from its memory representation as a byte
2063 array in native endianness.
2065 As the target platform's native endianness is used, portable code
2066 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2067 appropriate instead.
2069 [`from_be_bytes`]: #method.from_be_bytes
2070 [`from_le_bytes`]: #method.from_le_bytes
2075 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
2080 assert_eq!(value, ", $swap_op, ");
2083 When starting from a slice rather than an array, fallible conversion APIs can be used:
2086 #![feature(try_from)]
2087 use std::convert::TryInto;
2089 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2090 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2092 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
2095 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2096 #[rustc_const_unstable(feature = "const_int_conversion")]
2098 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2099 unsafe { mem::transmute(bytes) }
2107 int_impl! { i8, i8, u8, 8, -128, 127, "", "", 2, "-0x7e", "0xa", "0x12", "0x12", "0x48",
2108 "[0x12]", "[0x12]" }
2113 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234", "0x3412",
2114 "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]" }
2119 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2120 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2121 "[0x12, 0x34, 0x56, 0x78]" }
2126 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "", 12,
2127 "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2128 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2129 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]" }
2134 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
2135 170141183460469231731687303715884105727, "", "", 16,
2136 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
2137 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
2138 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
2139 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2140 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
2141 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]" }
2144 #[cfg(target_pointer_width = "16")]
2147 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234",
2148 "0x3412", "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]" }
2151 #[cfg(target_pointer_width = "32")]
2154 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2155 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2156 "[0x12, 0x34, 0x56, 0x78]" }
2159 #[cfg(target_pointer_width = "64")]
2162 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "",
2163 12, "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2164 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2165 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]" }
2168 // `Int` + `UnsignedInt` implemented for unsigned integers
2169 macro_rules! uint_impl {
2170 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr,
2171 $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
2172 $reversed:expr, $le_bytes:expr, $be_bytes:expr) => {
2174 concat!("Returns the smallest value that can be represented by this integer type.
2181 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), 0);", $EndFeature, "
2183 #[stable(feature = "rust1", since = "1.0.0")]
2186 pub const fn min_value() -> Self { 0 }
2190 concat!("Returns the largest value that can be represented by this integer type.
2197 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ",
2198 stringify!($MaxV), ");", $EndFeature, "
2200 #[stable(feature = "rust1", since = "1.0.0")]
2203 pub const fn max_value() -> Self { !0 }
2207 concat!("Converts a string slice in a given base to an integer.
2209 The string is expected to be an optional `+` sign
2211 Leading and trailing whitespace represent an error.
2212 Digits are a subset of these characters, depending on `radix`:
2220 This function panics if `radix` is not in the range from 2 to 36.
2227 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
2230 #[stable(feature = "rust1", since = "1.0.0")]
2231 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
2232 from_str_radix(src, radix)
2237 concat!("Returns the number of ones in the binary representation of `self`.
2244 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
2246 assert_eq!(n.count_ones(), 3);", $EndFeature, "
2248 #[stable(feature = "rust1", since = "1.0.0")]
2249 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_ops"))]
2251 pub const fn count_ones(self) -> u32 {
2253 unsafe { intrinsics::ctpop(self as $ActualT) as u32 }
2255 { intrinsics::ctpop(self as $ActualT) as u32 }
2260 concat!("Returns the number of zeros in the binary representation of `self`.
2267 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 0);", $EndFeature, "
2269 #[stable(feature = "rust1", since = "1.0.0")]
2270 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_ops"))]
2272 pub const fn count_zeros(self) -> u32 {
2273 (!self).count_ones()
2278 concat!("Returns the number of leading zeros in the binary representation of `self`.
2285 ", $Feature, "let n = ", stringify!($SelfT), "::max_value() >> 2;
2287 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
2289 #[stable(feature = "rust1", since = "1.0.0")]
2290 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_ops"))]
2292 pub const fn leading_zeros(self) -> u32 {
2294 unsafe { intrinsics::ctlz(self as $ActualT) as u32 }
2296 { intrinsics::ctlz(self as $ActualT) as u32 }
2301 concat!("Returns the number of trailing zeros in the binary representation
2309 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
2311 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
2313 #[stable(feature = "rust1", since = "1.0.0")]
2314 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_ops"))]
2316 pub const fn trailing_zeros(self) -> u32 {
2318 unsafe { intrinsics::cttz(self) as u32 }
2320 { intrinsics::cttz(self) as u32 }
2325 concat!("Shifts the bits to the left by a specified amount, `n`,
2326 wrapping the truncated bits to the end of the resulting integer.
2328 Please note this isn't the same operation as `<<`!
2335 let n = ", $rot_op, stringify!($SelfT), ";
2336 let m = ", $rot_result, ";
2338 assert_eq!(n.rotate_left(", $rot, "), m);
2340 #[stable(feature = "rust1", since = "1.0.0")]
2341 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_rotate"))]
2343 pub const fn rotate_left(self, n: u32) -> Self {
2345 unsafe { intrinsics::rotate_left(self, n as $SelfT) }
2347 intrinsics::rotate_left(self, n as $SelfT)
2352 concat!("Shifts the bits to the right by a specified amount, `n`,
2353 wrapping the truncated bits to the beginning of the resulting
2356 Please note this isn't the same operation as `>>`!
2363 let n = ", $rot_result, stringify!($SelfT), ";
2364 let m = ", $rot_op, ";
2366 assert_eq!(n.rotate_right(", $rot, "), m);
2368 #[stable(feature = "rust1", since = "1.0.0")]
2369 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_rotate"))]
2371 pub const fn rotate_right(self, n: u32) -> Self {
2373 unsafe { intrinsics::rotate_right(self, n as $SelfT) }
2375 intrinsics::rotate_right(self, n as $SelfT)
2381 Reverses the byte order of the integer.
2388 let n = ", $swap_op, stringify!($SelfT), ";
2389 let m = n.swap_bytes();
2391 assert_eq!(m, ", $swapped, ");
2393 #[stable(feature = "rust1", since = "1.0.0")]
2394 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_ops"))]
2396 pub const fn swap_bytes(self) -> Self {
2398 unsafe { intrinsics::bswap(self as $ActualT) as Self }
2400 { intrinsics::bswap(self as $ActualT) as Self }
2405 concat!("Reverses the bit pattern of the integer.
2412 #![feature(reverse_bits)]
2414 let n = ", $swap_op, stringify!($SelfT), ";
2415 let m = n.reverse_bits();
2417 assert_eq!(m, ", $reversed, ");
2419 #[unstable(feature = "reverse_bits", issue = "48763")]
2420 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_conversion"))]
2422 pub const fn reverse_bits(self) -> Self {
2424 unsafe { intrinsics::bitreverse(self as $ActualT) as Self }
2426 { intrinsics::bitreverse(self as $ActualT) as Self }
2431 concat!("Converts an integer from big endian to the target's endianness.
2433 On big endian this is a no-op. On little endian the bytes are
2441 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2443 if cfg!(target_endian = \"big\") {
2444 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
2446 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
2449 #[stable(feature = "rust1", since = "1.0.0")]
2450 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_ops"))]
2452 pub const fn from_be(x: Self) -> Self {
2453 #[cfg(target_endian = "big")]
2457 #[cfg(not(target_endian = "big"))]
2465 concat!("Converts an integer from little endian to the target's endianness.
2467 On little endian this is a no-op. On big endian the bytes are
2475 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2477 if cfg!(target_endian = \"little\") {
2478 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
2480 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
2483 #[stable(feature = "rust1", since = "1.0.0")]
2484 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_ops"))]
2486 pub const fn from_le(x: Self) -> Self {
2487 #[cfg(target_endian = "little")]
2491 #[cfg(not(target_endian = "little"))]
2499 concat!("Converts `self` to big endian from the target's endianness.
2501 On big endian this is a no-op. On little endian the bytes are
2509 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2511 if cfg!(target_endian = \"big\") {
2512 assert_eq!(n.to_be(), n)
2514 assert_eq!(n.to_be(), n.swap_bytes())
2517 #[stable(feature = "rust1", since = "1.0.0")]
2518 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_ops"))]
2520 pub const fn to_be(self) -> Self { // or not to be?
2521 #[cfg(target_endian = "big")]
2525 #[cfg(not(target_endian = "big"))]
2533 concat!("Converts `self` to little endian from the target's endianness.
2535 On little endian this is a no-op. On big endian the bytes are
2543 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2545 if cfg!(target_endian = \"little\") {
2546 assert_eq!(n.to_le(), n)
2548 assert_eq!(n.to_le(), n.swap_bytes())
2551 #[stable(feature = "rust1", since = "1.0.0")]
2552 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_ops"))]
2554 pub const fn to_le(self) -> Self {
2555 #[cfg(target_endian = "little")]
2559 #[cfg(not(target_endian = "little"))]
2567 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2568 if overflow occurred.
2575 ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), ",
2576 "Some(", stringify!($SelfT), "::max_value() - 1));
2577 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);", $EndFeature, "
2579 #[stable(feature = "rust1", since = "1.0.0")]
2581 pub fn checked_add(self, rhs: Self) -> Option<Self> {
2582 let (a, b) = self.overflowing_add(rhs);
2583 if b {None} else {Some(a)}
2588 concat!("Checked integer subtraction. Computes `self - rhs`, returning
2589 `None` if overflow occurred.
2596 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
2597 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
2599 #[stable(feature = "rust1", since = "1.0.0")]
2601 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
2602 let (a, b) = self.overflowing_sub(rhs);
2603 if b {None} else {Some(a)}
2608 concat!("Checked integer multiplication. Computes `self * rhs`, returning
2609 `None` if overflow occurred.
2616 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
2617 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, "
2619 #[stable(feature = "rust1", since = "1.0.0")]
2621 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
2622 let (a, b) = self.overflowing_mul(rhs);
2623 if b {None} else {Some(a)}
2628 concat!("Checked integer division. Computes `self / rhs`, returning `None`
2636 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2637 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2639 #[stable(feature = "rust1", since = "1.0.0")]
2641 pub fn checked_div(self, rhs: Self) -> Option<Self> {
2644 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
2650 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
2658 #![feature(euclidean_division)]
2659 assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));
2660 assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);
2662 #[unstable(feature = "euclidean_division", issue = "49048")]
2664 pub fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
2668 Some(self.div_euclid(rhs))
2675 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
2683 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
2684 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
2686 #[stable(feature = "wrapping", since = "1.7.0")]
2688 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
2692 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
2698 concat!("Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
2706 #![feature(euclidean_division)]
2707 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
2708 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
2710 #[unstable(feature = "euclidean_division", issue = "49048")]
2712 pub fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
2716 Some(self.rem_euclid(rhs))
2722 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
2725 Note that negating any positive integer will overflow.
2732 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
2733 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
2735 #[stable(feature = "wrapping", since = "1.7.0")]
2737 pub fn checked_neg(self) -> Option<Self> {
2738 let (a, b) = self.overflowing_neg();
2739 if b {None} else {Some(a)}
2744 concat!("Checked shift left. Computes `self << rhs`, returning `None`
2745 if `rhs` is larger than or equal to the number of bits in `self`.
2752 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
2753 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
2755 #[stable(feature = "wrapping", since = "1.7.0")]
2757 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
2758 let (a, b) = self.overflowing_shl(rhs);
2759 if b {None} else {Some(a)}
2764 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
2765 if `rhs` is larger than or equal to the number of bits in `self`.
2772 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
2773 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
2775 #[stable(feature = "wrapping", since = "1.7.0")]
2777 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
2778 let (a, b) = self.overflowing_shr(rhs);
2779 if b {None} else {Some(a)}
2784 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
2792 #![feature(no_panic_pow)]
2793 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
2794 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, "
2796 #[unstable(feature = "no_panic_pow", issue = "48320")]
2798 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
2799 let mut base = self;
2800 let mut acc: Self = 1;
2804 acc = acc.checked_mul(base)?;
2807 base = base.checked_mul(base)?;
2810 // Deal with the final bit of the exponent separately, since
2811 // squaring the base afterwards is not necessary and may cause a
2812 // needless overflow.
2814 acc = acc.checked_mul(base)?;
2822 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
2823 the numeric bounds instead of overflowing.
2830 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
2831 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
2833 #[stable(feature = "rust1", since = "1.0.0")]
2835 pub fn saturating_add(self, rhs: Self) -> Self {
2836 match self.checked_add(rhs) {
2838 None => Self::max_value(),
2844 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
2845 at the numeric bounds instead of overflowing.
2852 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
2853 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
2855 #[stable(feature = "rust1", since = "1.0.0")]
2857 pub fn saturating_sub(self, rhs: Self) -> Self {
2858 match self.checked_sub(rhs) {
2860 None => Self::min_value(),
2866 concat!("Saturating integer multiplication. Computes `self * rhs`,
2867 saturating at the numeric bounds instead of overflowing.
2874 ", $Feature, "use std::", stringify!($SelfT), ";
2876 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
2877 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
2878 "::MAX);", $EndFeature, "
2880 #[stable(feature = "wrapping", since = "1.7.0")]
2882 pub fn saturating_mul(self, rhs: Self) -> Self {
2883 self.checked_mul(rhs).unwrap_or(Self::max_value())
2888 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
2889 saturating at the numeric bounds instead of overflowing.
2896 #![feature(no_panic_pow)]
2897 ", $Feature, "use std::", stringify!($SelfT), ";
2899 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
2900 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
2903 #[unstable(feature = "no_panic_pow", issue = "48320")]
2905 pub fn saturating_pow(self, exp: u32) -> Self {
2906 match self.checked_pow(exp) {
2908 None => Self::max_value(),
2914 concat!("Wrapping (modular) addition. Computes `self + rhs`,
2915 wrapping around at the boundary of the type.
2922 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
2923 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
2926 #[stable(feature = "rust1", since = "1.0.0")]
2927 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_wrapping"))]
2929 pub const fn wrapping_add(self, rhs: Self) -> Self {
2932 intrinsics::overflowing_add(self, rhs)
2935 intrinsics::overflowing_add(self, rhs)
2940 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
2941 wrapping around at the boundary of the type.
2948 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
2949 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
2952 #[stable(feature = "rust1", since = "1.0.0")]
2953 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_wrapping"))]
2955 pub const fn wrapping_sub(self, rhs: Self) -> Self {
2958 intrinsics::overflowing_sub(self, rhs)
2961 intrinsics::overflowing_sub(self, rhs)
2965 /// Wrapping (modular) multiplication. Computes `self *
2966 /// rhs`, wrapping around at the boundary of the type.
2972 /// Please note that this example is shared between integer types.
2973 /// Which explains why `u8` is used here.
2976 /// assert_eq!(10u8.wrapping_mul(12), 120);
2977 /// assert_eq!(25u8.wrapping_mul(12), 44);
2979 #[stable(feature = "rust1", since = "1.0.0")]
2980 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_wrapping"))]
2982 pub const fn wrapping_mul(self, rhs: Self) -> Self {
2985 intrinsics::overflowing_mul(self, rhs)
2988 intrinsics::overflowing_mul(self, rhs)
2992 concat!("Wrapping (modular) division. Computes `self / rhs`.
2993 Wrapped division on unsigned types is just normal division.
2994 There's no way wrapping could ever happen.
2995 This function exists, so that all operations
2996 are accounted for in the wrapping operations.
3003 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
3005 #[stable(feature = "num_wrapping", since = "1.2.0")]
3007 pub fn wrapping_div(self, rhs: Self) -> Self {
3013 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
3014 Wrapped division on unsigned types is just normal division.
3015 There's no way wrapping could ever happen.
3016 This function exists, so that all operations
3017 are accounted for in the wrapping operations.
3018 Since, for the positive integers, all common
3019 definitions of division are equal, this
3020 is exactly equal to `self.wrapping_div(rhs)`.
3027 #![feature(euclidean_division)]
3028 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
3030 #[unstable(feature = "euclidean_division", issue = "49048")]
3032 pub fn wrapping_div_euclid(self, rhs: Self) -> Self {
3038 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
3039 Wrapped remainder calculation on unsigned types is
3040 just the regular remainder calculation.
3041 There's no way wrapping could ever happen.
3042 This function exists, so that all operations
3043 are accounted for in the wrapping operations.
3050 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
3052 #[stable(feature = "num_wrapping", since = "1.2.0")]
3054 pub fn wrapping_rem(self, rhs: Self) -> Self {
3060 concat!("Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
3061 Wrapped modulo calculation on unsigned types is
3062 just the regular remainder calculation.
3063 There's no way wrapping could ever happen.
3064 This function exists, so that all operations
3065 are accounted for in the wrapping operations.
3066 Since, for the positive integers, all common
3067 definitions of division are equal, this
3068 is exactly equal to `self.wrapping_rem(rhs)`.
3075 #![feature(euclidean_division)]
3076 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
3078 #[unstable(feature = "euclidean_division", issue = "49048")]
3080 pub fn wrapping_rem_euclid(self, rhs: Self) -> Self {
3085 /// Wrapping (modular) negation. Computes `-self`,
3086 /// wrapping around at the boundary of the type.
3088 /// Since unsigned types do not have negative equivalents
3089 /// all applications of this function will wrap (except for `-0`).
3090 /// For values smaller than the corresponding signed type's maximum
3091 /// the result is the same as casting the corresponding signed value.
3092 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
3093 /// `MAX` is the corresponding signed type's maximum.
3099 /// Please note that this example is shared between integer types.
3100 /// Which explains why `i8` is used here.
3103 /// assert_eq!(100i8.wrapping_neg(), -100);
3104 /// assert_eq!((-128i8).wrapping_neg(), -128);
3106 #[stable(feature = "num_wrapping", since = "1.2.0")]
3108 pub fn wrapping_neg(self) -> Self {
3109 self.overflowing_neg().0
3113 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
3114 where `mask` removes any high-order bits of `rhs` that
3115 would cause the shift to exceed the bitwidth of the type.
3117 Note that this is *not* the same as a rotate-left; the
3118 RHS of a wrapping shift-left is restricted to the range
3119 of the type, rather than the bits shifted out of the LHS
3120 being returned to the other end. The primitive integer
3121 types all implement a `rotate_left` function, which may
3122 be what you want instead.
3129 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
3130 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
3132 #[stable(feature = "num_wrapping", since = "1.2.0")]
3133 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_wrapping"))]
3135 pub const fn wrapping_shl(self, rhs: u32) -> Self {
3137 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
3143 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
3144 where `mask` removes any high-order bits of `rhs` that
3145 would cause the shift to exceed the bitwidth of the type.
3147 Note that this is *not* the same as a rotate-right; the
3148 RHS of a wrapping shift-right is restricted to the range
3149 of the type, rather than the bits shifted out of the LHS
3150 being returned to the other end. The primitive integer
3151 types all implement a `rotate_right` function, which may
3152 be what you want instead.
3159 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
3160 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
3162 #[stable(feature = "num_wrapping", since = "1.2.0")]
3163 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_wrapping"))]
3165 pub const fn wrapping_shr(self, rhs: u32) -> Self {
3167 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
3173 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
3174 wrapping around at the boundary of the type.
3181 #![feature(no_panic_pow)]
3182 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
3183 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
3185 #[unstable(feature = "no_panic_pow", issue = "48320")]
3187 pub fn wrapping_pow(self, mut exp: u32) -> Self {
3188 let mut base = self;
3189 let mut acc: Self = 1;
3193 acc = acc.wrapping_mul(base);
3196 base = base.wrapping_mul(base);
3199 // Deal with the final bit of the exponent separately, since
3200 // squaring the base afterwards is not necessary and may cause a
3201 // needless overflow.
3203 acc = acc.wrapping_mul(base);
3211 concat!("Calculates `self` + `rhs`
3213 Returns a tuple of the addition along with a boolean indicating
3214 whether an arithmetic overflow would occur. If an overflow would
3215 have occurred then the wrapped value is returned.
3222 ", $Feature, "use std::", stringify!($SelfT), ";
3224 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
3225 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
3227 #[stable(feature = "wrapping", since = "1.7.0")]
3228 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_overflowing"))]
3230 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
3232 let (a, b) = unsafe {
3233 intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT)
3236 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
3242 concat!("Calculates `self` - `rhs`
3244 Returns a tuple of the subtraction along with a boolean indicating
3245 whether an arithmetic overflow would occur. If an overflow would
3246 have occurred then the wrapped value is returned.
3253 ", $Feature, "use std::", stringify!($SelfT), ";
3255 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
3256 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
3259 #[stable(feature = "wrapping", since = "1.7.0")]
3260 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_overflowing"))]
3262 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3264 let (a, b) = unsafe {
3265 intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT)
3268 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
3273 /// Calculates the multiplication of `self` and `rhs`.
3275 /// Returns a tuple of the multiplication along with a boolean
3276 /// indicating whether an arithmetic overflow would occur. If an
3277 /// overflow would have occurred then the wrapped value is returned.
3283 /// Please note that this example is shared between integer types.
3284 /// Which explains why `u32` is used here.
3287 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3288 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3290 #[stable(feature = "wrapping", since = "1.7.0")]
3291 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_overflowing"))]
3293 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3295 let (a, b) = unsafe {
3296 intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT)
3299 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
3304 concat!("Calculates the divisor when `self` is divided by `rhs`.
3306 Returns a tuple of the divisor along with a boolean indicating
3307 whether an arithmetic overflow would occur. Note that for unsigned
3308 integers overflow never occurs, so the second value is always
3313 This function will panic if `rhs` is 0.
3320 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
3323 #[stable(feature = "wrapping", since = "1.7.0")]
3324 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3330 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
3332 Returns a tuple of the divisor along with a boolean indicating
3333 whether an arithmetic overflow would occur. Note that for unsigned
3334 integers overflow never occurs, so the second value is always
3336 Since, for the positive integers, all common
3337 definitions of division are equal, this
3338 is exactly equal to `self.overflowing_div(rhs)`.
3342 This function will panic if `rhs` is 0.
3349 #![feature(euclidean_division)]
3350 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
3353 #[unstable(feature = "euclidean_division", issue = "49048")]
3354 pub fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
3360 concat!("Calculates the remainder when `self` is divided by `rhs`.
3362 Returns a tuple of the remainder after dividing along with a boolean
3363 indicating whether an arithmetic overflow would occur. Note that for
3364 unsigned integers overflow never occurs, so the second value is
3369 This function will panic if `rhs` is 0.
3376 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3379 #[stable(feature = "wrapping", since = "1.7.0")]
3380 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3386 concat!("Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
3388 Returns a tuple of the modulo after dividing along with a boolean
3389 indicating whether an arithmetic overflow would occur. Note that for
3390 unsigned integers overflow never occurs, so the second value is
3392 Since, for the positive integers, all common
3393 definitions of division are equal, this operation
3394 is exactly equal to `self.overflowing_rem(rhs)`.
3398 This function will panic if `rhs` is 0.
3405 #![feature(euclidean_division)]
3406 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
3409 #[unstable(feature = "euclidean_division", issue = "49048")]
3410 pub fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
3416 concat!("Negates self in an overflowing fashion.
3418 Returns `!self + 1` using wrapping operations to return the value
3419 that represents the negation of this unsigned value. Note that for
3420 positive unsigned values overflow always occurs, but negating 0 does
3428 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3429 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3430 ", true));", $EndFeature, "
3433 #[stable(feature = "wrapping", since = "1.7.0")]
3434 pub fn overflowing_neg(self) -> (Self, bool) {
3435 ((!self).wrapping_add(1), self != 0)
3440 concat!("Shifts self left by `rhs` bits.
3442 Returns a tuple of the shifted version of self along with a boolean
3443 indicating whether the shift value was larger than or equal to the
3444 number of bits. If the shift value is too large, then value is
3445 masked (N-1) where N is the number of bits, and this value is then
3446 used to perform the shift.
3453 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3454 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3456 #[stable(feature = "wrapping", since = "1.7.0")]
3457 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_overflowing"))]
3459 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3460 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3465 concat!("Shifts self right by `rhs` bits.
3467 Returns a tuple of the shifted version of self along with a boolean
3468 indicating whether the shift value was larger than or equal to the
3469 number of bits. If the shift value is too large, then value is
3470 masked (N-1) where N is the number of bits, and this value is then
3471 used to perform the shift.
3478 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
3479 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
3481 #[stable(feature = "wrapping", since = "1.7.0")]
3482 #[cfg_attr(stage0, rustc_const_unstable(feature = "const_int_overflowing"))]
3484 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3485 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
3490 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3492 Returns a tuple of the exponentiation along with a bool indicating
3493 whether an overflow happened.
3500 #![feature(no_panic_pow)]
3501 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
3502 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
3504 #[unstable(feature = "no_panic_pow", issue = "48320")]
3506 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3507 let mut base = self;
3508 let mut acc: Self = 1;
3509 let mut overflown = false;
3510 // Scratch space for storing results of overflowing_mul.
3515 r = acc.overflowing_mul(base);
3520 r = base.overflowing_mul(base);
3525 // Deal with the final bit of the exponent separately, since
3526 // squaring the base afterwards is not necessary and may cause a
3527 // needless overflow.
3529 r = acc.overflowing_mul(base);
3539 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3546 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
3548 #[stable(feature = "rust1", since = "1.0.0")]
3550 #[rustc_inherit_overflow_checks]
3551 pub fn pow(self, mut exp: u32) -> Self {
3552 let mut base = self;
3563 // Deal with the final bit of the exponent separately, since
3564 // squaring the base afterwards is not necessary and may cause a
3565 // needless overflow.
3575 concat!("Performs Euclidean division.
3577 Since, for the positive integers, all common
3578 definitions of division are equal, this
3579 is exactly equal to `self / rhs`.
3586 #![feature(euclidean_division)]
3587 assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type
3589 #[unstable(feature = "euclidean_division", issue = "49048")]
3591 #[rustc_inherit_overflow_checks]
3592 pub fn div_euclid(self, rhs: Self) -> Self {
3599 concat!("Calculates the least remainder of `self (mod rhs)`.
3601 Since, for the positive integers, all common
3602 definitions of division are equal, this
3603 is exactly equal to `self % rhs`.
3610 #![feature(euclidean_division)]
3611 assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type
3613 #[unstable(feature = "euclidean_division", issue = "49048")]
3615 #[rustc_inherit_overflow_checks]
3616 pub fn rem_euclid(self, rhs: Self) -> Self {
3622 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
3629 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
3630 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
3632 #[stable(feature = "rust1", since = "1.0.0")]
3634 pub fn is_power_of_two(self) -> bool {
3635 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
3639 // Returns one less than next power of two.
3640 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
3642 // 8u8.one_less_than_next_power_of_two() == 7
3643 // 6u8.one_less_than_next_power_of_two() == 7
3645 // This method cannot overflow, as in the `next_power_of_two`
3646 // overflow cases it instead ends up returning the maximum value
3647 // of the type, and can return 0 for 0.
3649 fn one_less_than_next_power_of_two(self) -> Self {
3650 if self <= 1 { return 0; }
3652 // Because `p > 0`, it cannot consist entirely of leading zeros.
3653 // That means the shift is always in-bounds, and some processors
3654 // (such as intel pre-haswell) have more efficient ctlz
3655 // intrinsics when the argument is non-zero.
3657 let z = unsafe { intrinsics::ctlz_nonzero(p) };
3658 <$SelfT>::max_value() >> z
3662 concat!("Returns the smallest power of two greater than or equal to `self`.
3664 When return value overflows (i.e., `self > (1 << (N-1))` for type
3665 `uN`), it panics in debug mode and return value is wrapped to 0 in
3666 release mode (the only situation in which method can return 0).
3673 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
3674 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
3676 #[stable(feature = "rust1", since = "1.0.0")]
3678 pub fn next_power_of_two(self) -> Self {
3679 // Call the trait to get overflow checks
3680 ops::Add::add(self.one_less_than_next_power_of_two(), 1)
3685 concat!("Returns the smallest power of two greater than or equal to `n`. If
3686 the next power of two is greater than the type's maximum value,
3687 `None` is returned, otherwise the power of two is wrapped in `Some`.
3694 ", $Feature, "assert_eq!(2", stringify!($SelfT),
3695 ".checked_next_power_of_two(), Some(2));
3696 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
3697 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
3701 #[stable(feature = "rust1", since = "1.0.0")]
3702 pub fn checked_next_power_of_two(self) -> Option<Self> {
3703 self.one_less_than_next_power_of_two().checked_add(1)
3708 concat!("Returns the smallest power of two greater than or equal to `n`. If
3709 the next power of two is greater than the type's maximum value,
3710 the return value is wrapped to `0`.
3717 #![feature(wrapping_next_power_of_two)]
3719 assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);
3720 assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);
3721 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_next_power_of_two(), 0);",
3724 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
3725 reason = "needs decision on wrapping behaviour")]
3726 pub fn wrapping_next_power_of_two(self) -> Self {
3727 self.one_less_than_next_power_of_two().wrapping_add(1)
3732 concat!("Return the memory representation of this integer as a byte array in
3733 big-endian (network) byte order.
3738 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
3739 assert_eq!(bytes, ", $be_bytes, ");
3741 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3742 #[rustc_const_unstable(feature = "const_int_conversion")]
3744 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
3745 self.to_be().to_ne_bytes()
3750 concat!("Return the memory representation of this integer as a byte array in
3751 little-endian byte order.
3756 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
3757 assert_eq!(bytes, ", $le_bytes, ");
3759 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3760 #[rustc_const_unstable(feature = "const_int_conversion")]
3762 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
3763 self.to_le().to_ne_bytes()
3769 Return the memory representation of this integer as a byte array in
3772 As the target platform's native endianness is used, portable code
3773 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
3776 [`to_be_bytes`]: #method.to_be_bytes
3777 [`to_le_bytes`]: #method.to_le_bytes
3782 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
3783 assert_eq!(bytes, if cfg!(target_endian = \"big\") {
3789 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3790 #[rustc_const_unstable(feature = "const_int_conversion")]
3792 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
3793 unsafe { mem::transmute(self) }
3798 concat!("Create an integer value from its representation as a byte array in
3804 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
3805 assert_eq!(value, ", $swap_op, ");
3808 When starting from a slice rather than an array, fallible conversion APIs can be used:
3811 #![feature(try_from)]
3812 use std::convert::TryInto;
3814 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
3815 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
3817 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
3820 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3821 #[rustc_const_unstable(feature = "const_int_conversion")]
3823 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3824 Self::from_be(Self::from_ne_bytes(bytes))
3830 Create an integer value from its representation as a byte array in
3836 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
3837 assert_eq!(value, ", $swap_op, ");
3840 When starting from a slice rather than an array, fallible conversion APIs can be used:
3843 #![feature(try_from)]
3844 use std::convert::TryInto;
3846 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
3847 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
3849 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
3852 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3853 #[rustc_const_unstable(feature = "const_int_conversion")]
3855 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3856 Self::from_le(Self::from_ne_bytes(bytes))
3861 concat!("Create an integer value from its memory representation as a byte
3862 array in native endianness.
3864 As the target platform's native endianness is used, portable code
3865 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
3866 appropriate instead.
3868 [`from_be_bytes`]: #method.from_be_bytes
3869 [`from_le_bytes`]: #method.from_le_bytes
3874 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
3879 assert_eq!(value, ", $swap_op, ");
3882 When starting from a slice rather than an array, fallible conversion APIs can be used:
3885 #![feature(try_from)]
3886 use std::convert::TryInto;
3888 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
3889 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
3891 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
3894 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3895 #[rustc_const_unstable(feature = "const_int_conversion")]
3897 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3898 unsafe { mem::transmute(bytes) }
3906 uint_impl! { u8, u8, 8, 255, "", "", 2, "0x82", "0xa", "0x12", "0x12", "0x48", "[0x12]",
3910 /// Checks if the value is within the ASCII range.
3915 /// let ascii = 97u8;
3916 /// let non_ascii = 150u8;
3918 /// assert!(ascii.is_ascii());
3919 /// assert!(!non_ascii.is_ascii());
3921 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3923 pub fn is_ascii(&self) -> bool {
3927 /// Makes a copy of the value in its ASCII upper case equivalent.
3929 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3930 /// but non-ASCII letters are unchanged.
3932 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
3937 /// let lowercase_a = 97u8;
3939 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
3942 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
3943 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3945 pub fn to_ascii_uppercase(&self) -> u8 {
3946 ASCII_UPPERCASE_MAP[*self as usize]
3949 /// Makes a copy of the value in its ASCII lower case equivalent.
3951 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3952 /// but non-ASCII letters are unchanged.
3954 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
3959 /// let uppercase_a = 65u8;
3961 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
3964 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
3965 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3967 pub fn to_ascii_lowercase(&self) -> u8 {
3968 ASCII_LOWERCASE_MAP[*self as usize]
3971 /// Checks that two values are an ASCII case-insensitive match.
3973 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
3978 /// let lowercase_a = 97u8;
3979 /// let uppercase_a = 65u8;
3981 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
3983 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3985 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
3986 self.to_ascii_lowercase() == other.to_ascii_lowercase()
3989 /// Converts this value to its ASCII upper case equivalent in-place.
3991 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3992 /// but non-ASCII letters are unchanged.
3994 /// To return a new uppercased value without modifying the existing one, use
3995 /// [`to_ascii_uppercase`].
4000 /// let mut byte = b'a';
4002 /// byte.make_ascii_uppercase();
4004 /// assert_eq!(b'A', byte);
4007 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
4008 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4010 pub fn make_ascii_uppercase(&mut self) {
4011 *self = self.to_ascii_uppercase();
4014 /// Converts this value to its ASCII lower case equivalent in-place.
4016 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4017 /// but non-ASCII letters are unchanged.
4019 /// To return a new lowercased value without modifying the existing one, use
4020 /// [`to_ascii_lowercase`].
4025 /// let mut byte = b'A';
4027 /// byte.make_ascii_lowercase();
4029 /// assert_eq!(b'a', byte);
4032 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
4033 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4035 pub fn make_ascii_lowercase(&mut self) {
4036 *self = self.to_ascii_lowercase();
4039 /// Checks if the value is an ASCII alphabetic character:
4041 /// - U+0041 'A' ... U+005A 'Z', or
4042 /// - U+0061 'a' ... U+007A 'z'.
4047 /// let uppercase_a = b'A';
4048 /// let uppercase_g = b'G';
4051 /// let zero = b'0';
4052 /// let percent = b'%';
4053 /// let space = b' ';
4055 /// let esc = 0x1b_u8;
4057 /// assert!(uppercase_a.is_ascii_alphabetic());
4058 /// assert!(uppercase_g.is_ascii_alphabetic());
4059 /// assert!(a.is_ascii_alphabetic());
4060 /// assert!(g.is_ascii_alphabetic());
4061 /// assert!(!zero.is_ascii_alphabetic());
4062 /// assert!(!percent.is_ascii_alphabetic());
4063 /// assert!(!space.is_ascii_alphabetic());
4064 /// assert!(!lf.is_ascii_alphabetic());
4065 /// assert!(!esc.is_ascii_alphabetic());
4067 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4069 pub fn is_ascii_alphabetic(&self) -> bool {
4070 if *self >= 0x80 { return false; }
4071 match ASCII_CHARACTER_CLASS[*self as usize] {
4072 L | Lx | U | Ux => true,
4077 /// Checks if the value is an ASCII uppercase character:
4078 /// U+0041 'A' ... U+005A 'Z'.
4083 /// let uppercase_a = b'A';
4084 /// let uppercase_g = b'G';
4087 /// let zero = b'0';
4088 /// let percent = b'%';
4089 /// let space = b' ';
4091 /// let esc = 0x1b_u8;
4093 /// assert!(uppercase_a.is_ascii_uppercase());
4094 /// assert!(uppercase_g.is_ascii_uppercase());
4095 /// assert!(!a.is_ascii_uppercase());
4096 /// assert!(!g.is_ascii_uppercase());
4097 /// assert!(!zero.is_ascii_uppercase());
4098 /// assert!(!percent.is_ascii_uppercase());
4099 /// assert!(!space.is_ascii_uppercase());
4100 /// assert!(!lf.is_ascii_uppercase());
4101 /// assert!(!esc.is_ascii_uppercase());
4103 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4105 pub fn is_ascii_uppercase(&self) -> bool {
4106 if *self >= 0x80 { return false }
4107 match ASCII_CHARACTER_CLASS[*self as usize] {
4113 /// Checks if the value is an ASCII lowercase character:
4114 /// U+0061 'a' ... U+007A 'z'.
4119 /// let uppercase_a = b'A';
4120 /// let uppercase_g = b'G';
4123 /// let zero = b'0';
4124 /// let percent = b'%';
4125 /// let space = b' ';
4127 /// let esc = 0x1b_u8;
4129 /// assert!(!uppercase_a.is_ascii_lowercase());
4130 /// assert!(!uppercase_g.is_ascii_lowercase());
4131 /// assert!(a.is_ascii_lowercase());
4132 /// assert!(g.is_ascii_lowercase());
4133 /// assert!(!zero.is_ascii_lowercase());
4134 /// assert!(!percent.is_ascii_lowercase());
4135 /// assert!(!space.is_ascii_lowercase());
4136 /// assert!(!lf.is_ascii_lowercase());
4137 /// assert!(!esc.is_ascii_lowercase());
4139 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4141 pub fn is_ascii_lowercase(&self) -> bool {
4142 if *self >= 0x80 { return false }
4143 match ASCII_CHARACTER_CLASS[*self as usize] {
4149 /// Checks if the value is an ASCII alphanumeric character:
4151 /// - U+0041 'A' ... U+005A 'Z', or
4152 /// - U+0061 'a' ... U+007A 'z', or
4153 /// - U+0030 '0' ... U+0039 '9'.
4158 /// let uppercase_a = b'A';
4159 /// let uppercase_g = b'G';
4162 /// let zero = b'0';
4163 /// let percent = b'%';
4164 /// let space = b' ';
4166 /// let esc = 0x1b_u8;
4168 /// assert!(uppercase_a.is_ascii_alphanumeric());
4169 /// assert!(uppercase_g.is_ascii_alphanumeric());
4170 /// assert!(a.is_ascii_alphanumeric());
4171 /// assert!(g.is_ascii_alphanumeric());
4172 /// assert!(zero.is_ascii_alphanumeric());
4173 /// assert!(!percent.is_ascii_alphanumeric());
4174 /// assert!(!space.is_ascii_alphanumeric());
4175 /// assert!(!lf.is_ascii_alphanumeric());
4176 /// assert!(!esc.is_ascii_alphanumeric());
4178 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4180 pub fn is_ascii_alphanumeric(&self) -> bool {
4181 if *self >= 0x80 { return false }
4182 match ASCII_CHARACTER_CLASS[*self as usize] {
4183 D | L | Lx | U | Ux => true,
4188 /// Checks if the value is an ASCII decimal digit:
4189 /// U+0030 '0' ... U+0039 '9'.
4194 /// let uppercase_a = b'A';
4195 /// let uppercase_g = b'G';
4198 /// let zero = b'0';
4199 /// let percent = b'%';
4200 /// let space = b' ';
4202 /// let esc = 0x1b_u8;
4204 /// assert!(!uppercase_a.is_ascii_digit());
4205 /// assert!(!uppercase_g.is_ascii_digit());
4206 /// assert!(!a.is_ascii_digit());
4207 /// assert!(!g.is_ascii_digit());
4208 /// assert!(zero.is_ascii_digit());
4209 /// assert!(!percent.is_ascii_digit());
4210 /// assert!(!space.is_ascii_digit());
4211 /// assert!(!lf.is_ascii_digit());
4212 /// assert!(!esc.is_ascii_digit());
4214 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4216 pub fn is_ascii_digit(&self) -> bool {
4217 if *self >= 0x80 { return false }
4218 match ASCII_CHARACTER_CLASS[*self as usize] {
4224 /// Checks if the value is an ASCII hexadecimal digit:
4226 /// - U+0030 '0' ... U+0039 '9', or
4227 /// - U+0041 'A' ... U+0046 'F', or
4228 /// - U+0061 'a' ... U+0066 'f'.
4233 /// let uppercase_a = b'A';
4234 /// let uppercase_g = b'G';
4237 /// let zero = b'0';
4238 /// let percent = b'%';
4239 /// let space = b' ';
4241 /// let esc = 0x1b_u8;
4243 /// assert!(uppercase_a.is_ascii_hexdigit());
4244 /// assert!(!uppercase_g.is_ascii_hexdigit());
4245 /// assert!(a.is_ascii_hexdigit());
4246 /// assert!(!g.is_ascii_hexdigit());
4247 /// assert!(zero.is_ascii_hexdigit());
4248 /// assert!(!percent.is_ascii_hexdigit());
4249 /// assert!(!space.is_ascii_hexdigit());
4250 /// assert!(!lf.is_ascii_hexdigit());
4251 /// assert!(!esc.is_ascii_hexdigit());
4253 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4255 pub fn is_ascii_hexdigit(&self) -> bool {
4256 if *self >= 0x80 { return false }
4257 match ASCII_CHARACTER_CLASS[*self as usize] {
4258 D | Lx | Ux => true,
4263 /// Checks if the value is an ASCII punctuation character:
4265 /// - U+0021 ... U+002F `! " # $ % & ' ( ) * + , - . /`, or
4266 /// - U+003A ... U+0040 `: ; < = > ? @`, or
4267 /// - U+005B ... U+0060 ``[ \ ] ^ _ ` ``, or
4268 /// - U+007B ... U+007E `{ | } ~`
4273 /// let uppercase_a = b'A';
4274 /// let uppercase_g = b'G';
4277 /// let zero = b'0';
4278 /// let percent = b'%';
4279 /// let space = b' ';
4281 /// let esc = 0x1b_u8;
4283 /// assert!(!uppercase_a.is_ascii_punctuation());
4284 /// assert!(!uppercase_g.is_ascii_punctuation());
4285 /// assert!(!a.is_ascii_punctuation());
4286 /// assert!(!g.is_ascii_punctuation());
4287 /// assert!(!zero.is_ascii_punctuation());
4288 /// assert!(percent.is_ascii_punctuation());
4289 /// assert!(!space.is_ascii_punctuation());
4290 /// assert!(!lf.is_ascii_punctuation());
4291 /// assert!(!esc.is_ascii_punctuation());
4293 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4295 pub fn is_ascii_punctuation(&self) -> bool {
4296 if *self >= 0x80 { return false }
4297 match ASCII_CHARACTER_CLASS[*self as usize] {
4303 /// Checks if the value is an ASCII graphic character:
4304 /// U+0021 '!' ... U+007E '~'.
4309 /// let uppercase_a = b'A';
4310 /// let uppercase_g = b'G';
4313 /// let zero = b'0';
4314 /// let percent = b'%';
4315 /// let space = b' ';
4317 /// let esc = 0x1b_u8;
4319 /// assert!(uppercase_a.is_ascii_graphic());
4320 /// assert!(uppercase_g.is_ascii_graphic());
4321 /// assert!(a.is_ascii_graphic());
4322 /// assert!(g.is_ascii_graphic());
4323 /// assert!(zero.is_ascii_graphic());
4324 /// assert!(percent.is_ascii_graphic());
4325 /// assert!(!space.is_ascii_graphic());
4326 /// assert!(!lf.is_ascii_graphic());
4327 /// assert!(!esc.is_ascii_graphic());
4329 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4331 pub fn is_ascii_graphic(&self) -> bool {
4332 if *self >= 0x80 { return false; }
4333 match ASCII_CHARACTER_CLASS[*self as usize] {
4334 Ux | U | Lx | L | D | P => true,
4339 /// Checks if the value is an ASCII whitespace character:
4340 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
4341 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
4343 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
4344 /// whitespace][infra-aw]. There are several other definitions in
4345 /// wide use. For instance, [the POSIX locale][pct] includes
4346 /// U+000B VERTICAL TAB as well as all the above characters,
4347 /// but—from the very same specification—[the default rule for
4348 /// "field splitting" in the Bourne shell][bfs] considers *only*
4349 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
4351 /// If you are writing a program that will process an existing
4352 /// file format, check what that format's definition of whitespace is
4353 /// before using this function.
4355 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
4356 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
4357 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
4362 /// let uppercase_a = b'A';
4363 /// let uppercase_g = b'G';
4366 /// let zero = b'0';
4367 /// let percent = b'%';
4368 /// let space = b' ';
4370 /// let esc = 0x1b_u8;
4372 /// assert!(!uppercase_a.is_ascii_whitespace());
4373 /// assert!(!uppercase_g.is_ascii_whitespace());
4374 /// assert!(!a.is_ascii_whitespace());
4375 /// assert!(!g.is_ascii_whitespace());
4376 /// assert!(!zero.is_ascii_whitespace());
4377 /// assert!(!percent.is_ascii_whitespace());
4378 /// assert!(space.is_ascii_whitespace());
4379 /// assert!(lf.is_ascii_whitespace());
4380 /// assert!(!esc.is_ascii_whitespace());
4382 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4384 pub fn is_ascii_whitespace(&self) -> bool {
4385 if *self >= 0x80 { return false; }
4386 match ASCII_CHARACTER_CLASS[*self as usize] {
4392 /// Checks if the value is an ASCII control character:
4393 /// U+0000 NUL ... U+001F UNIT SEPARATOR, or U+007F DELETE.
4394 /// Note that most ASCII whitespace characters are control
4395 /// characters, but SPACE is not.
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_control());
4411 /// assert!(!uppercase_g.is_ascii_control());
4412 /// assert!(!a.is_ascii_control());
4413 /// assert!(!g.is_ascii_control());
4414 /// assert!(!zero.is_ascii_control());
4415 /// assert!(!percent.is_ascii_control());
4416 /// assert!(!space.is_ascii_control());
4417 /// assert!(lf.is_ascii_control());
4418 /// assert!(esc.is_ascii_control());
4420 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4422 pub fn is_ascii_control(&self) -> bool {
4423 if *self >= 0x80 { return false; }
4424 match ASCII_CHARACTER_CLASS[*self as usize] {
4433 uint_impl! { u16, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4434 "[0x34, 0x12]", "[0x12, 0x34]" }
4439 uint_impl! { u32, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4440 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]" }
4445 uint_impl! { u64, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4446 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4447 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4448 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]" }
4453 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "", 16,
4454 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
4455 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
4456 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
4457 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4458 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
4459 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]" }
4462 #[cfg(target_pointer_width = "16")]
4465 uint_impl! { usize, u16, 16, 65536, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4466 "[0x34, 0x12]", "[0x12, 0x34]" }
4468 #[cfg(target_pointer_width = "32")]
4471 uint_impl! { usize, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4472 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]" }
4475 #[cfg(target_pointer_width = "64")]
4478 uint_impl! { usize, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4479 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4480 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4481 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]" }
4484 /// A classification of floating point numbers.
4486 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
4487 /// their documentation for more.
4489 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
4490 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
4495 /// use std::num::FpCategory;
4498 /// let num = 12.4_f32;
4499 /// let inf = f32::INFINITY;
4500 /// let zero = 0f32;
4501 /// let sub: f32 = 1.1754942e-38;
4502 /// let nan = f32::NAN;
4504 /// assert_eq!(num.classify(), FpCategory::Normal);
4505 /// assert_eq!(inf.classify(), FpCategory::Infinite);
4506 /// assert_eq!(zero.classify(), FpCategory::Zero);
4507 /// assert_eq!(nan.classify(), FpCategory::Nan);
4508 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
4510 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
4511 #[stable(feature = "rust1", since = "1.0.0")]
4512 pub enum FpCategory {
4513 /// "Not a Number", often obtained by dividing by zero.
4514 #[stable(feature = "rust1", since = "1.0.0")]
4517 /// Positive or negative infinity.
4518 #[stable(feature = "rust1", since = "1.0.0")]
4521 /// Positive or negative zero.
4522 #[stable(feature = "rust1", since = "1.0.0")]
4525 /// De-normalized floating point representation (less precise than `Normal`).
4526 #[stable(feature = "rust1", since = "1.0.0")]
4529 /// A regular floating point number.
4530 #[stable(feature = "rust1", since = "1.0.0")]
4534 macro_rules! from_str_radix_int_impl {
4536 #[stable(feature = "rust1", since = "1.0.0")]
4537 impl FromStr for $t {
4538 type Err = ParseIntError;
4539 fn from_str(src: &str) -> Result<Self, ParseIntError> {
4540 from_str_radix(src, 10)
4545 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
4547 /// The error type returned when a checked integral type conversion fails.
4548 #[unstable(feature = "try_from", issue = "33417")]
4549 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
4550 pub struct TryFromIntError(());
4552 impl TryFromIntError {
4553 #[unstable(feature = "int_error_internals",
4554 reason = "available through Error trait and this method should \
4555 not be exposed publicly",
4558 pub fn __description(&self) -> &str {
4559 "out of range integral type conversion attempted"
4563 #[unstable(feature = "try_from", issue = "33417")]
4564 impl fmt::Display for TryFromIntError {
4565 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4566 self.__description().fmt(fmt)
4570 #[unstable(feature = "try_from", issue = "33417")]
4571 impl From<!> for TryFromIntError {
4572 fn from(never: !) -> TryFromIntError {
4577 // no possible bounds violation
4578 macro_rules! try_from_unbounded {
4579 ($source:ty, $($target:ty),*) => {$(
4580 #[unstable(feature = "try_from", issue = "33417")]
4581 impl TryFrom<$source> for $target {
4582 type Error = TryFromIntError;
4585 fn try_from(value: $source) -> Result<Self, Self::Error> {
4586 Ok(value as $target)
4592 // only negative bounds
4593 macro_rules! try_from_lower_bounded {
4594 ($source:ty, $($target:ty),*) => {$(
4595 #[unstable(feature = "try_from", issue = "33417")]
4596 impl TryFrom<$source> for $target {
4597 type Error = TryFromIntError;
4600 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4604 Err(TryFromIntError(()))
4611 // unsigned to signed (only positive bound)
4612 macro_rules! try_from_upper_bounded {
4613 ($source:ty, $($target:ty),*) => {$(
4614 #[unstable(feature = "try_from", issue = "33417")]
4615 impl TryFrom<$source> for $target {
4616 type Error = TryFromIntError;
4619 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4620 if u > (<$target>::max_value() as $source) {
4621 Err(TryFromIntError(()))
4631 macro_rules! try_from_both_bounded {
4632 ($source:ty, $($target:ty),*) => {$(
4633 #[unstable(feature = "try_from", issue = "33417")]
4634 impl TryFrom<$source> for $target {
4635 type Error = TryFromIntError;
4638 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4639 let min = <$target>::min_value() as $source;
4640 let max = <$target>::max_value() as $source;
4641 if u < min || u > max {
4642 Err(TryFromIntError(()))
4652 ($mac:ident, $source:ty, $($target:ty),*) => {$(
4653 $mac!($target, $source);
4657 /// intra-sign conversions
4658 try_from_upper_bounded!(u16, u8);
4659 try_from_upper_bounded!(u32, u16, u8);
4660 try_from_upper_bounded!(u64, u32, u16, u8);
4661 try_from_upper_bounded!(u128, u64, u32, u16, u8);
4663 try_from_both_bounded!(i16, i8);
4664 try_from_both_bounded!(i32, i16, i8);
4665 try_from_both_bounded!(i64, i32, i16, i8);
4666 try_from_both_bounded!(i128, i64, i32, i16, i8);
4668 // unsigned-to-signed
4669 try_from_upper_bounded!(u8, i8);
4670 try_from_upper_bounded!(u16, i8, i16);
4671 try_from_upper_bounded!(u32, i8, i16, i32);
4672 try_from_upper_bounded!(u64, i8, i16, i32, i64);
4673 try_from_upper_bounded!(u128, i8, i16, i32, i64, i128);
4675 // signed-to-unsigned
4676 try_from_lower_bounded!(i8, u8, u16, u32, u64, u128);
4677 try_from_lower_bounded!(i16, u16, u32, u64, u128);
4678 try_from_lower_bounded!(i32, u32, u64, u128);
4679 try_from_lower_bounded!(i64, u64, u128);
4680 try_from_lower_bounded!(i128, u128);
4681 try_from_both_bounded!(i16, u8);
4682 try_from_both_bounded!(i32, u16, u8);
4683 try_from_both_bounded!(i64, u32, u16, u8);
4684 try_from_both_bounded!(i128, u64, u32, u16, u8);
4687 try_from_upper_bounded!(usize, isize);
4688 try_from_lower_bounded!(isize, usize);
4690 #[cfg(target_pointer_width = "16")]
4691 mod ptr_try_from_impls {
4692 use super::TryFromIntError;
4693 use convert::TryFrom;
4695 try_from_upper_bounded!(usize, u8);
4696 try_from_unbounded!(usize, u16, u32, u64, u128);
4697 try_from_upper_bounded!(usize, i8, i16);
4698 try_from_unbounded!(usize, i32, i64, i128);
4700 try_from_both_bounded!(isize, u8);
4701 try_from_lower_bounded!(isize, u16, u32, u64, u128);
4702 try_from_both_bounded!(isize, i8);
4703 try_from_unbounded!(isize, i16, i32, i64, i128);
4705 rev!(try_from_upper_bounded, usize, u32, u64, u128);
4706 rev!(try_from_lower_bounded, usize, i8, i16);
4707 rev!(try_from_both_bounded, usize, i32, i64, i128);
4709 rev!(try_from_upper_bounded, isize, u16, u32, u64, u128);
4710 rev!(try_from_both_bounded, isize, i32, i64, i128);
4713 #[cfg(target_pointer_width = "32")]
4714 mod ptr_try_from_impls {
4715 use super::TryFromIntError;
4716 use convert::TryFrom;
4718 try_from_upper_bounded!(usize, u8, u16);
4719 try_from_unbounded!(usize, u32, u64, u128);
4720 try_from_upper_bounded!(usize, i8, i16, i32);
4721 try_from_unbounded!(usize, i64, i128);
4723 try_from_both_bounded!(isize, u8, u16);
4724 try_from_lower_bounded!(isize, u32, u64, u128);
4725 try_from_both_bounded!(isize, i8, i16);
4726 try_from_unbounded!(isize, i32, i64, i128);
4728 rev!(try_from_unbounded, usize, u32);
4729 rev!(try_from_upper_bounded, usize, u64, u128);
4730 rev!(try_from_lower_bounded, usize, i8, i16, i32);
4731 rev!(try_from_both_bounded, usize, i64, i128);
4733 rev!(try_from_unbounded, isize, u16);
4734 rev!(try_from_upper_bounded, isize, u32, u64, u128);
4735 rev!(try_from_unbounded, isize, i32);
4736 rev!(try_from_both_bounded, isize, i64, i128);
4739 #[cfg(target_pointer_width = "64")]
4740 mod ptr_try_from_impls {
4741 use super::TryFromIntError;
4742 use convert::TryFrom;
4744 try_from_upper_bounded!(usize, u8, u16, u32);
4745 try_from_unbounded!(usize, u64, u128);
4746 try_from_upper_bounded!(usize, i8, i16, i32, i64);
4747 try_from_unbounded!(usize, i128);
4749 try_from_both_bounded!(isize, u8, u16, u32);
4750 try_from_lower_bounded!(isize, u64, u128);
4751 try_from_both_bounded!(isize, i8, i16, i32);
4752 try_from_unbounded!(isize, i64, i128);
4754 rev!(try_from_unbounded, usize, u32, u64);
4755 rev!(try_from_upper_bounded, usize, u128);
4756 rev!(try_from_lower_bounded, usize, i8, i16, i32, i64);
4757 rev!(try_from_both_bounded, usize, i128);
4759 rev!(try_from_unbounded, isize, u16, u32);
4760 rev!(try_from_upper_bounded, isize, u64, u128);
4761 rev!(try_from_unbounded, isize, i32, i64);
4762 rev!(try_from_both_bounded, isize, i128);
4766 trait FromStrRadixHelper: PartialOrd + Copy {
4767 fn min_value() -> Self;
4768 fn max_value() -> Self;
4769 fn from_u32(u: u32) -> Self;
4770 fn checked_mul(&self, other: u32) -> Option<Self>;
4771 fn checked_sub(&self, other: u32) -> Option<Self>;
4772 fn checked_add(&self, other: u32) -> Option<Self>;
4776 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
4778 fn min_value() -> Self { Self::min_value() }
4780 fn max_value() -> Self { Self::max_value() }
4782 fn from_u32(u: u32) -> Self { u as Self }
4784 fn checked_mul(&self, other: u32) -> Option<Self> {
4785 Self::checked_mul(*self, other as Self)
4788 fn checked_sub(&self, other: u32) -> Option<Self> {
4789 Self::checked_sub(*self, other as Self)
4792 fn checked_add(&self, other: u32) -> Option<Self> {
4793 Self::checked_add(*self, other as Self)
4797 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
4799 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
4800 use self::IntErrorKind::*;
4801 use self::ParseIntError as PIE;
4803 assert!(radix >= 2 && radix <= 36,
4804 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
4808 return Err(PIE { kind: Empty });
4811 let is_signed_ty = T::from_u32(0) > T::min_value();
4813 // all valid digits are ascii, so we will just iterate over the utf8 bytes
4814 // and cast them to chars. .to_digit() will safely return None for anything
4815 // other than a valid ascii digit for the given radix, including the first-byte
4816 // of multi-byte sequences
4817 let src = src.as_bytes();
4819 let (is_positive, digits) = match src[0] {
4820 b'+' => (true, &src[1..]),
4821 b'-' if is_signed_ty => (false, &src[1..]),
4825 if digits.is_empty() {
4826 return Err(PIE { kind: Empty });
4829 let mut result = T::from_u32(0);
4831 // The number is positive
4833 let x = match (c as char).to_digit(radix) {
4835 None => return Err(PIE { kind: InvalidDigit }),
4837 result = match result.checked_mul(radix) {
4838 Some(result) => result,
4839 None => return Err(PIE { kind: Overflow }),
4841 result = match result.checked_add(x) {
4842 Some(result) => result,
4843 None => return Err(PIE { kind: Overflow }),
4847 // The number is negative
4849 let x = match (c as char).to_digit(radix) {
4851 None => return Err(PIE { kind: InvalidDigit }),
4853 result = match result.checked_mul(radix) {
4854 Some(result) => result,
4855 None => return Err(PIE { kind: Underflow }),
4857 result = match result.checked_sub(x) {
4858 Some(result) => result,
4859 None => return Err(PIE { kind: Underflow }),
4866 /// An error which can be returned when parsing an integer.
4868 /// This error is used as the error type for the `from_str_radix()` functions
4869 /// on the primitive integer types, such as [`i8::from_str_radix`].
4871 /// # Potential causes
4873 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
4874 /// in the string e.g., when it is obtained from the standard input.
4875 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
4877 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
4878 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
4879 #[derive(Debug, Clone, PartialEq, Eq)]
4880 #[stable(feature = "rust1", since = "1.0.0")]
4881 pub struct ParseIntError {
4885 /// Enum to store the various types of errors that can cause parsing an integer to fail.
4886 #[unstable(feature = "int_error_matching",
4887 reason = "it can be useful to match errors when making error messages \
4888 for integer parsing",
4890 #[derive(Debug, Clone, PartialEq, Eq)]
4892 pub enum IntErrorKind {
4893 /// Value being parsed is empty.
4895 /// Among other causes, this variant will be constructed when parsing an empty string.
4897 /// Contains an invalid digit.
4899 /// Among other causes, this variant will be constructed when parsing a string that
4900 /// contains a letter.
4902 /// Integer is too large to store in target integer type.
4904 /// Integer is too small to store in target integer type.
4908 impl ParseIntError {
4909 /// Outputs the detailed cause of parsing an integer failing.
4910 #[unstable(feature = "int_error_matching",
4911 reason = "it can be useful to match errors when making error messages \
4912 for integer parsing",
4914 pub fn kind(&self) -> &IntErrorKind {
4917 #[unstable(feature = "int_error_internals",
4918 reason = "available through Error trait and this method should \
4919 not be exposed publicly",
4922 pub fn __description(&self) -> &str {
4924 IntErrorKind::Empty => "cannot parse integer from empty string",
4925 IntErrorKind::InvalidDigit => "invalid digit found in string",
4926 IntErrorKind::Overflow => "number too large to fit in target type",
4927 IntErrorKind::Underflow => "number too small to fit in target type",
4932 #[stable(feature = "rust1", since = "1.0.0")]
4933 impl fmt::Display for ParseIntError {
4934 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4935 self.__description().fmt(f)
4939 #[stable(feature = "rust1", since = "1.0.0")]
4940 pub use num::dec2flt::ParseFloatError;
4942 // Conversion traits for primitive integer and float types
4943 // Conversions T -> T are covered by a blanket impl and therefore excluded
4944 // Some conversions from and to usize/isize are not implemented due to portability concerns
4945 macro_rules! impl_from {
4946 ($Small: ty, $Large: ty, #[$attr:meta], $doc: expr) => {
4949 impl From<$Small> for $Large {
4951 fn from(small: $Small) -> $Large {
4956 ($Small: ty, $Large: ty, #[$attr:meta]) => {
4960 concat!("Converts `",
4968 macro_rules! impl_from_bool {
4969 ($target: ty, #[$attr:meta]) => {
4970 impl_from!(bool, $target, #[$attr], concat!("Converts a `bool` to a `",
4971 stringify!($target), "`. The resulting value is `0` for `false` and `1` for `true`
4977 assert_eq!(", stringify!($target), "::from(true), 1);
4978 assert_eq!(", stringify!($target), "::from(false), 0);
4984 impl_from_bool! { u8, #[stable(feature = "from_bool", since = "1.28.0")] }
4985 impl_from_bool! { u16, #[stable(feature = "from_bool", since = "1.28.0")] }
4986 impl_from_bool! { u32, #[stable(feature = "from_bool", since = "1.28.0")] }
4987 impl_from_bool! { u64, #[stable(feature = "from_bool", since = "1.28.0")] }
4988 impl_from_bool! { u128, #[stable(feature = "from_bool", since = "1.28.0")] }
4989 impl_from_bool! { usize, #[stable(feature = "from_bool", since = "1.28.0")] }
4990 impl_from_bool! { i8, #[stable(feature = "from_bool", since = "1.28.0")] }
4991 impl_from_bool! { i16, #[stable(feature = "from_bool", since = "1.28.0")] }
4992 impl_from_bool! { i32, #[stable(feature = "from_bool", since = "1.28.0")] }
4993 impl_from_bool! { i64, #[stable(feature = "from_bool", since = "1.28.0")] }
4994 impl_from_bool! { i128, #[stable(feature = "from_bool", since = "1.28.0")] }
4995 impl_from_bool! { isize, #[stable(feature = "from_bool", since = "1.28.0")] }
4997 // Unsigned -> Unsigned
4998 impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4999 impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5000 impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5001 impl_from! { u8, u128, #[stable(feature = "i128", since = "1.26.0")] }
5002 impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5003 impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5004 impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5005 impl_from! { u16, u128, #[stable(feature = "i128", since = "1.26.0")] }
5006 impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5007 impl_from! { u32, u128, #[stable(feature = "i128", since = "1.26.0")] }
5008 impl_from! { u64, u128, #[stable(feature = "i128", since = "1.26.0")] }
5011 impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5012 impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5013 impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5014 impl_from! { i8, i128, #[stable(feature = "i128", since = "1.26.0")] }
5015 impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5016 impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5017 impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5018 impl_from! { i16, i128, #[stable(feature = "i128", since = "1.26.0")] }
5019 impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5020 impl_from! { i32, i128, #[stable(feature = "i128", since = "1.26.0")] }
5021 impl_from! { i64, i128, #[stable(feature = "i128", since = "1.26.0")] }
5023 // Unsigned -> Signed
5024 impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5025 impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5026 impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5027 impl_from! { u8, i128, #[stable(feature = "i128", since = "1.26.0")] }
5028 impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5029 impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5030 impl_from! { u16, i128, #[stable(feature = "i128", since = "1.26.0")] }
5031 impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5032 impl_from! { u32, i128, #[stable(feature = "i128", since = "1.26.0")] }
5033 impl_from! { u64, i128, #[stable(feature = "i128", since = "1.26.0")] }
5035 // The C99 standard defines bounds on INTPTR_MIN, INTPTR_MAX, and UINTPTR_MAX
5036 // which imply that pointer-sized integers must be at least 16 bits:
5037 // https://port70.net/~nsz/c/c99/n1256.html#7.18.2.4
5038 impl_from! { u16, usize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
5039 impl_from! { u8, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
5040 impl_from! { i16, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
5042 // RISC-V defines the possibility of a 128-bit address space (RV128).
5044 // CHERI proposes 256-bit “capabilities”. Unclear if this would be relevant to usize/isize.
5045 // https://www.cl.cam.ac.uk/research/security/ctsrd/pdfs/20171017a-cheri-poster.pdf
5046 // http://www.csl.sri.com/users/neumann/2012resolve-cheri.pdf
5049 // Note: integers can only be represented with full precision in a float if
5050 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
5051 // Lossy float conversions are not implemented at this time.
5054 impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5055 impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5056 impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5057 impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5058 impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5060 // Unsigned -> Float
5061 impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5062 impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5063 impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5064 impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5065 impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5068 impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5070 static ASCII_LOWERCASE_MAP: [u8; 256] = [
5071 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
5072 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
5073 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
5074 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
5075 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
5076 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
5077 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
5078 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
5081 b'a', b'b', b'c', b'd', b'e', b'f', b'g',
5082 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
5083 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
5086 b'[', b'\\', b']', b'^', b'_',
5087 b'`', b'a', b'b', b'c', b'd', b'e', b'f', b'g',
5088 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
5089 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
5090 b'x', b'y', b'z', b'{', b'|', b'}', b'~', 0x7f,
5091 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
5092 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
5093 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
5094 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
5095 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
5096 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
5097 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
5098 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
5099 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
5100 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
5101 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
5102 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
5103 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
5104 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
5105 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
5106 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
5109 static ASCII_UPPERCASE_MAP: [u8; 256] = [
5110 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
5111 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
5112 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
5113 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
5114 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
5115 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
5116 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
5117 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
5118 b'@', b'A', b'B', b'C', b'D', b'E', b'F', b'G',
5119 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
5120 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
5121 b'X', b'Y', b'Z', b'[', b'\\', b']', b'^', b'_',
5124 b'A', b'B', b'C', b'D', b'E', b'F', b'G',
5125 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
5126 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
5129 b'{', b'|', b'}', b'~', 0x7f,
5130 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
5131 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
5132 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
5133 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
5134 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
5135 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
5136 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
5137 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
5138 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
5139 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
5140 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
5141 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
5142 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
5143 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
5144 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
5145 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
5148 enum AsciiCharacterClass {
5150 Cw, // control whitespace
5154 Lx, // lowercase hex digit
5156 Ux, // uppercase hex digit
5159 use self::AsciiCharacterClass::*;
5161 static ASCII_CHARACTER_CLASS: [AsciiCharacterClass; 128] = [
5162 // _0 _1 _2 _3 _4 _5 _6 _7 _8 _9 _a _b _c _d _e _f
5163 C, C, C, C, C, C, C, C, C, Cw,Cw,C, Cw,Cw,C, C, // 0_
5164 C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, // 1_
5165 W, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, // 2_
5166 D, D, D, D, D, D, D, D, D, D, P, P, P, P, P, P, // 3_
5167 P, Ux,Ux,Ux,Ux,Ux,Ux,U, U, U, U, U, U, U, U, U, // 4_
5168 U, U, U, U, U, U, U, U, U, U, U, P, P, P, P, P, // 5_
5169 P, Lx,Lx,Lx,Lx,Lx,Lx,L, L, L, L, L, L, L, L, L, // 6_
5170 L, L, L, L, L, L, L, L, L, L, L, P, P, P, P, C, // 7_