1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Numeric traits and functions for the built-in numeric types.
13 #![stable(feature = "rust1", since = "1.0.0")]
23 macro_rules! impl_nonzero_fmt {
24 ( ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
26 #[stable(feature = "nonzero", since = "1.28.0")]
27 impl fmt::$Trait for $Ty {
29 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
37 macro_rules! nonzero_integers {
38 ( $( $Ty: ident($Int: ty); )+ ) => {
40 /// An integer that is known not to equal zero.
42 /// This enables some memory layout optimization.
43 /// For example, `Option<NonZeroU32>` is the same size as `u32`:
46 /// use std::mem::size_of;
47 /// assert_eq!(size_of::<Option<std::num::NonZeroU32>>(), size_of::<u32>());
49 #[stable(feature = "nonzero", since = "1.28.0")]
50 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
52 pub struct $Ty(NonZero<$Int>);
55 /// Create a non-zero without checking the value.
59 /// The value must not be zero.
60 #[stable(feature = "nonzero", since = "1.28.0")]
62 pub const unsafe fn new_unchecked(n: $Int) -> Self {
66 /// Create a non-zero if the given value is not zero.
67 #[stable(feature = "nonzero", since = "1.28.0")]
69 pub fn new(n: $Int) -> Option<Self> {
77 /// Returns the value as a primitive type.
78 #[stable(feature = "nonzero", since = "1.28.0")]
80 pub fn get(self) -> $Int {
87 (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
102 /// Provides intentionally-wrapped arithmetic on `T`.
104 /// Operations like `+` on `u32` values is intended to never overflow,
105 /// and in some debug configurations overflow is detected and results
106 /// in a panic. While most arithmetic falls into this category, some
107 /// code explicitly expects and relies upon modular arithmetic (e.g.,
110 /// Wrapping arithmetic can be achieved either through methods like
111 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
112 /// all standard arithmetic operations on the underlying value are
113 /// intended to have wrapping semantics.
118 /// use std::num::Wrapping;
120 /// let zero = Wrapping(0u32);
121 /// let one = Wrapping(1u32);
123 /// assert_eq!(std::u32::MAX, (zero - one).0);
125 #[stable(feature = "rust1", since = "1.0.0")]
126 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
128 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")]
131 #[stable(feature = "rust1", since = "1.0.0")]
132 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
133 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
138 #[stable(feature = "wrapping_display", since = "1.10.0")]
139 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
140 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
145 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
146 impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
147 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
152 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
153 impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
154 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
159 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
160 impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
161 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
166 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
167 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
168 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
173 // All these modules are technically private and only exposed for coretests:
179 macro_rules! doc_comment {
180 ($x:expr, $($tt:tt)*) => {
188 // `Int` + `SignedInt` implemented for signed integers
189 macro_rules! int_impl {
190 ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $Min:expr, $Max:expr, $Feature:expr,
191 $EndFeature:expr) => {
193 concat!("Returns the smallest value that can be represented by this integer type.
200 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), ", stringify!($Min), ");",
203 #[stable(feature = "rust1", since = "1.0.0")]
205 pub const fn min_value() -> Self {
206 !0 ^ ((!0 as $UnsignedT) >> 1) as Self
211 concat!("Returns the largest value that can be represented by this integer type.
218 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ", stringify!($Max), ");",
221 #[stable(feature = "rust1", since = "1.0.0")]
223 pub const fn max_value() -> Self {
229 concat!("Converts a string slice in a given base to an integer.
231 The string is expected to be an optional `+` or `-` sign followed by digits.
232 Leading and trailing whitespace represent an error. Digits are a subset of these characters,
233 depending on `radix`:
241 This function panics if `radix` is not in the range from 2 to 36.
248 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
251 #[stable(feature = "rust1", since = "1.0.0")]
252 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
253 from_str_radix(src, radix)
258 concat!("Returns the number of ones in the binary representation of `self`.
265 ", $Feature, "let n = 0b100_0000", stringify!($SelfT), ";
267 assert_eq!(n.count_ones(), 1);",
271 #[stable(feature = "rust1", since = "1.0.0")]
272 #[rustc_const_unstable(feature = "const_int_ops")]
274 pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
278 concat!("Returns the number of zeros in the binary representation of `self`.
285 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 1);", $EndFeature, "
287 #[stable(feature = "rust1", since = "1.0.0")]
288 #[rustc_const_unstable(feature = "const_int_ops")]
290 pub const fn count_zeros(self) -> u32 {
296 concat!("Returns the number of leading zeros in the binary representation of `self`.
303 ", $Feature, "let n = -1", stringify!($SelfT), ";
305 assert_eq!(n.leading_zeros(), 0);",
308 #[stable(feature = "rust1", since = "1.0.0")]
309 #[rustc_const_unstable(feature = "const_int_ops")]
311 pub const fn leading_zeros(self) -> u32 {
312 (self as $UnsignedT).leading_zeros()
317 concat!("Returns the number of trailing zeros in the binary representation of `self`.
324 ", $Feature, "let n = -4", stringify!($SelfT), ";
326 assert_eq!(n.trailing_zeros(), 2);",
329 #[stable(feature = "rust1", since = "1.0.0")]
330 #[rustc_const_unstable(feature = "const_int_ops")]
332 pub const fn trailing_zeros(self) -> u32 {
333 (self as $UnsignedT).trailing_zeros()
337 /// Shifts the bits to the left by a specified amount, `n`,
338 /// wrapping the truncated bits to the end of the resulting integer.
340 /// Please note this isn't the same operation as `<<`!
344 /// Please note that this example is shared between integer types.
345 /// Which explains why `i64` is used here.
350 /// let n = 0x0123456789ABCDEFi64;
351 /// let m = -0x76543210FEDCBA99i64;
353 /// assert_eq!(n.rotate_left(32), m);
355 #[stable(feature = "rust1", since = "1.0.0")]
357 pub fn rotate_left(self, n: u32) -> Self {
358 (self as $UnsignedT).rotate_left(n) as Self
361 /// Shifts the bits to the right by a specified amount, `n`,
362 /// wrapping the truncated bits to the beginning of the resulting
365 /// Please note this isn't the same operation as `>>`!
369 /// Please note that this example is shared between integer types.
370 /// Which explains why `i64` is used here.
375 /// let n = 0x0123456789ABCDEFi64;
376 /// let m = -0xFEDCBA987654322i64;
378 /// assert_eq!(n.rotate_right(4), m);
380 #[stable(feature = "rust1", since = "1.0.0")]
382 pub fn rotate_right(self, n: u32) -> Self {
383 (self as $UnsignedT).rotate_right(n) as Self
386 /// Reverses the byte order of the integer.
390 /// Please note that this example is shared between integer types.
391 /// Which explains why `i16` is used here.
396 /// let n: i16 = 0b0000000_01010101;
397 /// assert_eq!(n, 85);
399 /// let m = n.swap_bytes();
401 /// assert_eq!(m, 0b01010101_00000000);
402 /// assert_eq!(m, 21760);
404 #[stable(feature = "rust1", since = "1.0.0")]
405 #[rustc_const_unstable(feature = "const_int_ops")]
407 pub const fn swap_bytes(self) -> Self {
408 (self as $UnsignedT).swap_bytes() as Self
411 /// Reverses the bit pattern of the integer.
415 /// Please note that this example is shared between integer types.
416 /// Which explains why `i16` is used here.
421 /// #![feature(reverse_bits)]
423 /// let n: i16 = 0b0000000_01010101;
424 /// assert_eq!(n, 85);
426 /// let m = n.reverse_bits();
428 /// assert_eq!(m as u16, 0b10101010_00000000);
429 /// assert_eq!(m, -22016);
431 #[unstable(feature = "reverse_bits", issue = "48763")]
433 pub fn reverse_bits(self) -> Self {
434 (self as $UnsignedT).reverse_bits() as Self
438 concat!("Converts an integer from big endian to the target's endianness.
440 On big endian this is a no-op. On little endian the bytes are swapped.
447 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
449 if cfg!(target_endian = \"big\") {
450 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
452 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
456 #[stable(feature = "rust1", since = "1.0.0")]
457 #[rustc_const_unstable(feature = "const_int_ops")]
459 pub const fn from_be(x: Self) -> Self {
460 #[cfg(target_endian = "big")]
464 #[cfg(not(target_endian = "big"))]
472 concat!("Converts an integer from little endian to the target's endianness.
474 On little endian this is a no-op. On big endian the bytes are swapped.
481 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
483 if cfg!(target_endian = \"little\") {
484 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
486 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
490 #[stable(feature = "rust1", since = "1.0.0")]
491 #[rustc_const_unstable(feature = "const_int_ops")]
493 pub const fn from_le(x: Self) -> Self {
494 #[cfg(target_endian = "little")]
498 #[cfg(not(target_endian = "little"))]
506 concat!("Converts `self` to big endian from the target's endianness.
508 On big endian this is a no-op. On little endian the bytes are swapped.
515 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
517 if cfg!(target_endian = \"big\") {
518 assert_eq!(n.to_be(), n)
520 assert_eq!(n.to_be(), n.swap_bytes())
524 #[stable(feature = "rust1", since = "1.0.0")]
525 #[rustc_const_unstable(feature = "const_int_ops")]
527 pub const fn to_be(self) -> Self { // or not to be?
528 #[cfg(target_endian = "big")]
532 #[cfg(not(target_endian = "big"))]
540 concat!("Converts `self` to little endian from the target's endianness.
542 On little endian this is a no-op. On big endian the bytes are swapped.
549 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
551 if cfg!(target_endian = \"little\") {
552 assert_eq!(n.to_le(), n)
554 assert_eq!(n.to_le(), n.swap_bytes())
558 #[stable(feature = "rust1", since = "1.0.0")]
559 #[rustc_const_unstable(feature = "const_int_ops")]
561 pub const fn to_le(self) -> Self {
562 #[cfg(target_endian = "little")]
566 #[cfg(not(target_endian = "little"))]
574 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
575 if overflow occurred.
582 ", $Feature, "assert_eq!((", stringify!($SelfT),
583 "::max_value() - 2).checked_add(1), Some(", stringify!($SelfT), "::max_value() - 1));
584 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);",
587 #[stable(feature = "rust1", since = "1.0.0")]
589 pub fn checked_add(self, rhs: Self) -> Option<Self> {
590 let (a, b) = self.overflowing_add(rhs);
591 if b {None} else {Some(a)}
596 concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
604 ", $Feature, "assert_eq!((", stringify!($SelfT),
605 "::min_value() + 2).checked_sub(1), Some(", stringify!($SelfT), "::min_value() + 1));
606 assert_eq!((", stringify!($SelfT), "::min_value() + 2).checked_sub(3), None);",
609 #[stable(feature = "rust1", since = "1.0.0")]
611 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
612 let (a, b) = self.overflowing_sub(rhs);
613 if b {None} else {Some(a)}
618 concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
626 ", $Feature, "assert_eq!(", stringify!($SelfT),
627 "::max_value().checked_mul(1), Some(", stringify!($SelfT), "::max_value()));
628 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);",
631 #[stable(feature = "rust1", since = "1.0.0")]
633 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
634 let (a, b) = self.overflowing_mul(rhs);
635 if b {None} else {Some(a)}
640 concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
641 or the division results in overflow.
648 ", $Feature, "assert_eq!((", stringify!($SelfT),
649 "::min_value() + 1).checked_div(-1), Some(", stringify!($Max), "));
650 assert_eq!(", stringify!($SelfT), "::min_value().checked_div(-1), None);
651 assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
654 #[stable(feature = "rust1", since = "1.0.0")]
656 pub fn checked_div(self, rhs: Self) -> Option<Self> {
657 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
660 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
666 concat!("Checked Euclidean division. Computes `self.div_euc(rhs)`,
667 returning `None` if `rhs == 0` or the division results in overflow.
674 #![feature(euclidean_division)]
675 assert_eq!((", stringify!($SelfT),
676 "::min_value() + 1).checked_div_euc(-1), Some(", stringify!($Max), "));
677 assert_eq!(", stringify!($SelfT), "::min_value().checked_div_euc(-1), None);
678 assert_eq!((1", stringify!($SelfT), ").checked_div_euc(0), None);
680 #[unstable(feature = "euclidean_division", issue = "49048")]
682 pub fn checked_div_euc(self, rhs: Self) -> Option<Self> {
683 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
686 Some(self.div_euc(rhs))
692 concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
693 `rhs == 0` or the division results in overflow.
700 ", $Feature, "use std::", stringify!($SelfT), ";
702 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
703 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
704 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
707 #[stable(feature = "wrapping", since = "1.7.0")]
709 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
710 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
713 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
719 concat!("Checked Euclidean modulo. Computes `self.mod_euc(rhs)`, returning `None` if
720 `rhs == 0` or the division results in overflow.
727 #![feature(euclidean_division)]
728 use std::", stringify!($SelfT), ";
730 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(2), Some(1));
731 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(0), None);
732 assert_eq!(", stringify!($SelfT), "::MIN.checked_mod_euc(-1), None);
734 #[unstable(feature = "euclidean_division", issue = "49048")]
736 pub fn checked_mod_euc(self, rhs: Self) -> Option<Self> {
737 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
740 Some(self.mod_euc(rhs))
746 concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
753 ", $Feature, "use std::", stringify!($SelfT), ";
755 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
756 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
759 #[stable(feature = "wrapping", since = "1.7.0")]
761 pub fn checked_neg(self) -> Option<Self> {
762 let (a, b) = self.overflowing_neg();
763 if b {None} else {Some(a)}
768 concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
769 than or equal to the number of bits in `self`.
776 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
777 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
780 #[stable(feature = "wrapping", since = "1.7.0")]
782 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
783 let (a, b) = self.overflowing_shl(rhs);
784 if b {None} else {Some(a)}
789 concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
790 larger than or equal to the number of bits in `self`.
797 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
798 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
801 #[stable(feature = "wrapping", since = "1.7.0")]
803 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
804 let (a, b) = self.overflowing_shr(rhs);
805 if b {None} else {Some(a)}
810 concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
818 ", $Feature, "use std::", stringify!($SelfT), ";
820 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
821 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
824 #[stable(feature = "no_panic_abs", since = "1.13.0")]
826 pub fn checked_abs(self) -> Option<Self> {
827 if self.is_negative() {
836 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
844 #![feature(no_panic_pow)]
845 ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
846 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);",
850 #[unstable(feature = "no_panic_pow", issue = "48320")]
852 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
854 let mut acc: Self = 1;
858 acc = acc.checked_mul(base)?;
861 base = base.checked_mul(base)?;
864 // Deal with the final bit of the exponent separately, since
865 // squaring the base afterwards is not necessary and may cause a
866 // needless overflow.
868 acc = acc.checked_mul(base)?;
876 concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
877 bounds instead of overflowing.
884 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
885 assert_eq!(", stringify!($SelfT), "::max_value().saturating_add(100), ", stringify!($SelfT),
889 #[stable(feature = "rust1", since = "1.0.0")]
891 pub fn saturating_add(self, rhs: Self) -> Self {
892 match self.checked_add(rhs) {
894 None if rhs >= 0 => Self::max_value(),
895 None => Self::min_value(),
901 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
902 numeric bounds instead of overflowing.
909 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
910 assert_eq!(", stringify!($SelfT), "::min_value().saturating_sub(100), ", stringify!($SelfT),
914 #[stable(feature = "rust1", since = "1.0.0")]
916 pub fn saturating_sub(self, rhs: Self) -> Self {
917 match self.checked_sub(rhs) {
919 None if rhs >= 0 => Self::min_value(),
920 None => Self::max_value(),
926 concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
927 numeric bounds instead of overflowing.
934 ", $Feature, "use std::", stringify!($SelfT), ";
936 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
937 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
938 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
941 #[stable(feature = "wrapping", since = "1.7.0")]
943 pub fn saturating_mul(self, rhs: Self) -> Self {
944 self.checked_mul(rhs).unwrap_or_else(|| {
945 if (self < 0 && rhs < 0) || (self > 0 && rhs > 0) {
955 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
956 saturating at the numeric bounds instead of overflowing.
963 #![feature(no_panic_pow)]
964 ", $Feature, "use std::", stringify!($SelfT), ";
966 assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
967 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
968 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
971 #[unstable(feature = "no_panic_pow", issue = "48320")]
973 pub fn saturating_pow(self, exp: u32) -> Self {
974 match self.checked_pow(exp) {
976 None if self < 0 && exp % 2 == 1 => Self::min_value(),
977 None => Self::max_value(),
983 concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
984 boundary of the type.
991 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
992 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_add(2), ", stringify!($SelfT),
993 "::min_value() + 1);",
996 #[stable(feature = "rust1", since = "1.0.0")]
998 pub fn wrapping_add(self, rhs: Self) -> Self {
1000 intrinsics::overflowing_add(self, rhs)
1006 concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1007 boundary of the type.
1014 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
1015 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::max_value()), ",
1016 stringify!($SelfT), "::max_value());",
1019 #[stable(feature = "rust1", since = "1.0.0")]
1021 pub fn wrapping_sub(self, rhs: Self) -> Self {
1023 intrinsics::overflowing_sub(self, rhs)
1029 concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1030 the boundary of the type.
1037 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
1038 assert_eq!(11i8.wrapping_mul(12), -124);",
1041 #[stable(feature = "rust1", since = "1.0.0")]
1043 pub fn wrapping_mul(self, rhs: Self) -> Self {
1045 intrinsics::overflowing_mul(self, rhs)
1051 concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1052 boundary of the type.
1054 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1055 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1056 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1060 This function will panic if `rhs` is 0.
1067 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
1068 assert_eq!((-128i8).wrapping_div(-1), -128);",
1071 #[stable(feature = "num_wrapping", since = "1.2.0")]
1073 pub fn wrapping_div(self, rhs: Self) -> Self {
1074 self.overflowing_div(rhs).0
1079 concat!("Wrapping Euclidean division. Computes `self.div_euc(rhs)`,
1080 wrapping around at the boundary of the type.
1082 Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1083 for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1084 type. In this case, this method returns `MIN` itself.
1088 This function will panic if `rhs` is 0.
1095 #![feature(euclidean_division)]
1096 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euc(10), 10);
1097 assert_eq!((-128i8).wrapping_div_euc(-1), -128);
1099 #[unstable(feature = "euclidean_division", issue = "49048")]
1101 pub fn wrapping_div_euc(self, rhs: Self) -> Self {
1102 self.overflowing_div_euc(rhs).0
1107 concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1108 boundary of the type.
1110 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1111 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1112 this function returns `0`.
1116 This function will panic if `rhs` is 0.
1123 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
1124 assert_eq!((-128i8).wrapping_rem(-1), 0);",
1127 #[stable(feature = "num_wrapping", since = "1.2.0")]
1129 pub fn wrapping_rem(self, rhs: Self) -> Self {
1130 self.overflowing_rem(rhs).0
1135 concat!("Wrapping Euclidean modulo. Computes `self.mod_euc(rhs)`, wrapping around at the
1136 boundary of the type.
1138 Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1139 for the type). In this case, this method returns 0.
1143 This function will panic if `rhs` is 0.
1150 #![feature(euclidean_division)]
1151 assert_eq!(100", stringify!($SelfT), ".wrapping_mod_euc(10), 0);
1152 assert_eq!((-128i8).wrapping_mod_euc(-1), 0);
1154 #[unstable(feature = "euclidean_division", issue = "49048")]
1156 pub fn wrapping_mod_euc(self, rhs: Self) -> Self {
1157 self.overflowing_mod_euc(rhs).0
1162 concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1165 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1166 is the negative minimal value for the type); this is a positive value that is too large to represent
1167 in the type. In such a case, this function returns `MIN` itself.
1174 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
1175 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_neg(), ", stringify!($SelfT),
1179 #[stable(feature = "num_wrapping", since = "1.2.0")]
1181 pub fn wrapping_neg(self) -> Self {
1182 self.overflowing_neg().0
1187 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1188 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1190 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1191 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1192 The primitive integer types all implement a `rotate_left` function, which may be what you want
1200 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
1201 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
1204 #[stable(feature = "num_wrapping", since = "1.2.0")]
1206 pub fn wrapping_shl(self, rhs: u32) -> Self {
1208 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1214 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1215 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1217 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1218 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1219 end. The primitive integer types all implement a `rotate_right` function, which may be what you want
1227 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
1228 assert_eq!((-128i16).wrapping_shr(64), -128);",
1231 #[stable(feature = "num_wrapping", since = "1.2.0")]
1233 pub fn wrapping_shr(self, rhs: u32) -> Self {
1235 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1241 concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1242 the boundary of the type.
1244 The only case where such wrapping can occur is when one takes the absolute value of the negative
1245 minimal value for the type this is a positive value that is too large to represent in the type. In
1246 such a case, this function returns `MIN` itself.
1253 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
1254 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
1255 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_abs(), ", stringify!($SelfT),
1257 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1260 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1262 pub fn wrapping_abs(self) -> Self {
1263 if self.is_negative() {
1272 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1273 wrapping around at the boundary of the type.
1280 #![feature(no_panic_pow)]
1281 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);
1282 assert_eq!(3i8.wrapping_pow(5), -13);
1283 assert_eq!(3i8.wrapping_pow(6), -39);",
1286 #[unstable(feature = "no_panic_pow", issue = "48320")]
1288 pub fn wrapping_pow(self, mut exp: u32) -> Self {
1289 let mut base = self;
1290 let mut acc: Self = 1;
1294 acc = acc.wrapping_mul(base);
1297 base = base.wrapping_mul(base);
1300 // Deal with the final bit of the exponent separately, since
1301 // squaring the base afterwards is not necessary and may cause a
1302 // needless overflow.
1304 acc = acc.wrapping_mul(base);
1312 concat!("Calculates `self` + `rhs`
1314 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1315 occur. If an overflow would have occurred then the wrapped value is returned.
1322 ", $Feature, "use std::", stringify!($SelfT), ";
1324 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1325 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
1326 "::MIN, true));", $EndFeature, "
1329 #[stable(feature = "wrapping", since = "1.7.0")]
1330 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1331 let (a, b) = unsafe {
1332 intrinsics::add_with_overflow(self as $ActualT,
1340 concat!("Calculates `self` - `rhs`
1342 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1343 would occur. If an overflow would have occurred then the wrapped value is returned.
1350 ", $Feature, "use std::", stringify!($SelfT), ";
1352 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
1353 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
1354 "::MAX, true));", $EndFeature, "
1357 #[stable(feature = "wrapping", since = "1.7.0")]
1358 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1359 let (a, b) = unsafe {
1360 intrinsics::sub_with_overflow(self as $ActualT,
1368 concat!("Calculates the multiplication of `self` and `rhs`.
1370 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1371 would occur. If an overflow would have occurred then the wrapped value is returned.
1378 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1379 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1383 #[stable(feature = "wrapping", since = "1.7.0")]
1384 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1385 let (a, b) = unsafe {
1386 intrinsics::mul_with_overflow(self as $ActualT,
1394 concat!("Calculates the divisor when `self` is divided by `rhs`.
1396 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1397 occur. If an overflow would occur then self is returned.
1401 This function will panic if `rhs` is 0.
1408 ", $Feature, "use std::", stringify!($SelfT), ";
1410 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1411 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1416 #[stable(feature = "wrapping", since = "1.7.0")]
1417 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1418 if self == Self::min_value() && rhs == -1 {
1427 concat!("Calculates the quotient of Euclidean division `self.div_euc(rhs)`.
1429 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1430 occur. If an overflow would occur then `self` is returned.
1434 This function will panic if `rhs` is 0.
1441 #![feature(euclidean_division)]
1442 use std::", stringify!($SelfT), ";
1444 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euc(2), (2, false));
1445 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euc(-1), (", stringify!($SelfT),
1449 #[unstable(feature = "euclidean_division", issue = "49048")]
1450 pub fn overflowing_div_euc(self, rhs: Self) -> (Self, bool) {
1451 if self == Self::min_value() && rhs == -1 {
1454 (self.div_euc(rhs), false)
1460 concat!("Calculates the remainder when `self` is divided by `rhs`.
1462 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1463 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1467 This function will panic if `rhs` is 0.
1474 ", $Feature, "use std::", stringify!($SelfT), ";
1476 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1477 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1481 #[stable(feature = "wrapping", since = "1.7.0")]
1482 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1483 if self == Self::min_value() && rhs == -1 {
1493 concat!("Calculates the remainder `self.mod_euc(rhs)` by Euclidean division.
1495 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1496 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1500 This function will panic if `rhs` is 0.
1507 #![feature(euclidean_division)]
1508 use std::", stringify!($SelfT), ";
1510 assert_eq!(5", stringify!($SelfT), ".overflowing_mod_euc(2), (1, false));
1511 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_mod_euc(-1), (0, true));
1513 #[unstable(feature = "euclidean_division", issue = "49048")]
1515 pub fn overflowing_mod_euc(self, rhs: Self) -> (Self, bool) {
1516 if self == Self::min_value() && rhs == -1 {
1519 (self.mod_euc(rhs), false)
1526 concat!("Negates self, overflowing if this is equal to the minimum value.
1528 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1529 happened. If `self` is the minimum value (e.g. `i32::MIN` for values of type `i32`), then the
1530 minimum value will be returned again and `true` will be returned for an overflow happening.
1537 ", $Feature, "use std::", stringify!($SelfT), ";
1539 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1540 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1541 "::MIN, true));", $EndFeature, "
1544 #[stable(feature = "wrapping", since = "1.7.0")]
1545 pub fn overflowing_neg(self) -> (Self, bool) {
1546 if self == Self::min_value() {
1547 (Self::min_value(), true)
1555 concat!("Shifts self left by `rhs` bits.
1557 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1558 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1559 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1566 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1567 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1571 #[stable(feature = "wrapping", since = "1.7.0")]
1572 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1573 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1578 concat!("Shifts self right by `rhs` bits.
1580 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1581 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1582 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1589 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1590 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1594 #[stable(feature = "wrapping", since = "1.7.0")]
1595 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1596 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1601 concat!("Computes the absolute value of `self`.
1603 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1604 happened. If self is the minimum value (e.g. ", stringify!($SelfT), "::MIN for values of type
1605 ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1606 for an overflow happening.
1613 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1614 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1615 assert_eq!((", stringify!($SelfT), "::min_value()).overflowing_abs(), (", stringify!($SelfT),
1616 "::min_value(), true));",
1619 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1621 pub fn overflowing_abs(self) -> (Self, bool) {
1622 if self.is_negative() {
1623 self.overflowing_neg()
1631 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1633 Returns a tuple of the exponentiation along with a bool indicating
1634 whether an overflow happened.
1641 #![feature(no_panic_pow)]
1642 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));
1643 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
1646 #[unstable(feature = "no_panic_pow", issue = "48320")]
1648 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1649 let mut base = self;
1650 let mut acc: Self = 1;
1651 let mut overflown = false;
1652 // Scratch space for storing results of overflowing_mul.
1657 r = acc.overflowing_mul(base);
1662 r = base.overflowing_mul(base);
1667 // Deal with the final bit of the exponent separately, since
1668 // squaring the base afterwards is not necessary and may cause a
1669 // needless overflow.
1671 r = acc.overflowing_mul(base);
1681 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1688 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
1690 assert_eq!(x.pow(5), 32);",
1693 #[stable(feature = "rust1", since = "1.0.0")]
1695 #[rustc_inherit_overflow_checks]
1696 pub fn pow(self, mut exp: u32) -> Self {
1697 let mut base = self;
1708 // Deal with the final bit of the exponent separately, since
1709 // squaring the base afterwards is not necessary and may cause a
1710 // needless overflow.
1720 concat!("Calculates the quotient of Euclidean division of `self` by `rhs`.
1722 This computes the integer `n` such that `self = n * rhs + self.mod_euc(rhs)`.
1723 In other words, the result is `self / rhs` rounded to the integer `n`
1724 such that `self >= n * rhs`.
1728 This function will panic if `rhs` is 0.
1735 #![feature(euclidean_division)]
1736 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1739 assert_eq!(a.div_euc(b), 1); // 7 >= 4 * 1
1740 assert_eq!(a.div_euc(-b), -1); // 7 >= -4 * -1
1741 assert_eq!((-a).div_euc(b), -2); // -7 >= 4 * -2
1742 assert_eq!((-a).div_euc(-b), 2); // -7 >= -4 * 2
1744 #[unstable(feature = "euclidean_division", issue = "49048")]
1746 #[rustc_inherit_overflow_checks]
1747 pub fn div_euc(self, rhs: Self) -> Self {
1750 return if rhs > 0 { q - 1 } else { q + 1 }
1758 concat!("Calculates the remainder `self mod rhs` by Euclidean division.
1760 In particular, the result `n` satisfies `0 <= n < rhs.abs()`.
1764 This function will panic if `rhs` is 0.
1771 #![feature(euclidean_division)]
1772 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1775 assert_eq!(a.mod_euc(b), 3);
1776 assert_eq!((-a).mod_euc(b), 1);
1777 assert_eq!(a.mod_euc(-b), 3);
1778 assert_eq!((-a).mod_euc(-b), 1);
1780 #[unstable(feature = "euclidean_division", issue = "49048")]
1782 #[rustc_inherit_overflow_checks]
1783 pub fn mod_euc(self, rhs: Self) -> Self {
1798 concat!("Computes the absolute value of `self`.
1802 The absolute value of `", stringify!($SelfT), "::min_value()` cannot be represented as an
1803 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
1804 code in debug mode will trigger a panic on this case and optimized code will return `",
1805 stringify!($SelfT), "::min_value()` without a panic.
1812 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
1813 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
1816 #[stable(feature = "rust1", since = "1.0.0")]
1818 #[rustc_inherit_overflow_checks]
1819 pub fn abs(self) -> Self {
1820 if self.is_negative() {
1821 // Note that the #[inline] above means that the overflow
1822 // semantics of this negation depend on the crate we're being
1832 concat!("Returns a number representing sign of `self`.
1834 - `0` if the number is zero
1835 - `1` if the number is positive
1836 - `-1` if the number is negative
1843 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
1844 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
1845 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
1848 #[stable(feature = "rust1", since = "1.0.0")]
1850 pub fn signum(self) -> Self {
1860 concat!("Returns `true` if `self` is positive and `false` if the number is zero or
1868 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
1869 assert!(!(-10", stringify!($SelfT), ").is_positive());",
1872 #[stable(feature = "rust1", since = "1.0.0")]
1874 pub fn is_positive(self) -> bool { self > 0 }
1878 concat!("Returns `true` if `self` is negative and `false` if the number is zero or
1886 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
1887 assert!(!10", stringify!($SelfT), ".is_negative());",
1890 #[stable(feature = "rust1", since = "1.0.0")]
1892 pub fn is_negative(self) -> bool { self < 0 }
1895 /// Return the memory representation of this integer as a byte array.
1897 /// The target platform’s native endianness is used.
1898 /// Portable code likely wants to use this after [`to_be`] or [`to_le`].
1900 /// [`to_be`]: #method.to_be
1901 /// [`to_le`]: #method.to_le
1906 /// #![feature(int_to_from_bytes)]
1908 /// let bytes = i32::min_value().to_be().to_bytes();
1909 /// assert_eq!(bytes, [0x80, 0, 0, 0]);
1911 #[unstable(feature = "int_to_from_bytes", issue = "49792")]
1913 pub fn to_bytes(self) -> [u8; mem::size_of::<Self>()] {
1914 unsafe { mem::transmute(self) }
1917 /// Create an integer value from its memory representation as a byte array.
1919 /// The target platform’s native endianness is used.
1920 /// Portable code likely wants to use [`from_be`] or [`from_le`] after this.
1922 /// [`from_be`]: #method.from_be
1923 /// [`from_le`]: #method.from_le
1928 /// #![feature(int_to_from_bytes)]
1930 /// let int = i32::from_be(i32::from_bytes([0x80, 0, 0, 0]));
1931 /// assert_eq!(int, i32::min_value());
1933 #[unstable(feature = "int_to_from_bytes", issue = "49792")]
1935 pub fn from_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
1936 unsafe { mem::transmute(bytes) }
1943 int_impl! { i8, i8, u8, 8, -128, 127, "", "" }
1948 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "" }
1953 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "" }
1958 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "" }
1963 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
1964 170141183460469231731687303715884105727, "", "" }
1967 #[cfg(target_pointer_width = "16")]
1970 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "" }
1973 #[cfg(target_pointer_width = "32")]
1976 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "" }
1979 #[cfg(target_pointer_width = "64")]
1982 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "" }
1985 // Emits the correct `cttz` call, depending on the size of the type.
1986 macro_rules! uint_cttz_call {
1987 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
1988 // emits two conditional moves on x86_64. By promoting the value to
1989 // u16 and setting bit 8, we get better code without any conditional
1991 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
1992 // pending, remove this workaround once LLVM generates better code
1994 ($value:expr, 8) => { intrinsics::cttz($value as u16 | 0x100) };
1995 ($value:expr, $_BITS:expr) => { intrinsics::cttz($value) }
1998 // `Int` + `UnsignedInt` implemented for unsigned integers
1999 macro_rules! uint_impl {
2000 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr) => {
2002 concat!("Returns the smallest value that can be represented by this integer type.
2009 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), 0);", $EndFeature, "
2011 #[stable(feature = "rust1", since = "1.0.0")]
2013 pub const fn min_value() -> Self { 0 }
2017 concat!("Returns the largest value that can be represented by this integer type.
2024 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ",
2025 stringify!($MaxV), ");", $EndFeature, "
2027 #[stable(feature = "rust1", since = "1.0.0")]
2029 pub const fn max_value() -> Self { !0 }
2033 concat!("Converts a string slice in a given base to an integer.
2035 The string is expected to be an optional `+` sign
2037 Leading and trailing whitespace represent an error.
2038 Digits are a subset of these characters, depending on `radix`:
2046 This function panics if `radix` is not in the range from 2 to 36.
2053 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
2056 #[stable(feature = "rust1", since = "1.0.0")]
2057 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
2058 from_str_radix(src, radix)
2063 concat!("Returns the number of ones in the binary representation of `self`.
2070 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
2072 assert_eq!(n.count_ones(), 3);", $EndFeature, "
2074 #[stable(feature = "rust1", since = "1.0.0")]
2075 #[rustc_const_unstable(feature = "const_int_ops")]
2077 pub const fn count_ones(self) -> u32 {
2078 unsafe { intrinsics::ctpop(self as $ActualT) as u32 }
2083 concat!("Returns the number of zeros in the binary representation of `self`.
2090 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 0);", $EndFeature, "
2092 #[stable(feature = "rust1", since = "1.0.0")]
2093 #[rustc_const_unstable(feature = "const_int_ops")]
2095 pub const fn count_zeros(self) -> u32 {
2096 (!self).count_ones()
2101 concat!("Returns the number of leading zeros in the binary representation of `self`.
2108 ", $Feature, "let n = ", stringify!($SelfT), "::max_value() >> 2;
2110 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
2112 #[stable(feature = "rust1", since = "1.0.0")]
2113 #[rustc_const_unstable(feature = "const_int_ops")]
2115 pub const fn leading_zeros(self) -> u32 {
2116 unsafe { intrinsics::ctlz(self as $ActualT) as u32 }
2121 concat!("Returns the number of trailing zeros in the binary representation
2129 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
2131 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
2133 #[stable(feature = "rust1", since = "1.0.0")]
2134 #[rustc_const_unstable(feature = "const_int_ops")]
2136 pub const fn trailing_zeros(self) -> u32 {
2137 unsafe { uint_cttz_call!(self, $BITS) as u32 }
2141 /// Shifts the bits to the left by a specified amount, `n`,
2142 /// wrapping the truncated bits to the end of the resulting integer.
2144 /// Please note this isn't the same operation as `<<`!
2150 /// Please note that this example is shared between integer types.
2151 /// Which explains why `u64` is used here.
2154 /// let n = 0x0123456789ABCDEFu64;
2155 /// let m = 0x3456789ABCDEF012u64;
2157 /// assert_eq!(n.rotate_left(12), m);
2159 #[stable(feature = "rust1", since = "1.0.0")]
2161 pub fn rotate_left(self, n: u32) -> Self {
2162 // Protect against undefined behaviour for over-long bit shifts
2164 (self << n) | (self >> (($BITS - n) % $BITS))
2167 /// Shifts the bits to the right by a specified amount, `n`,
2168 /// wrapping the truncated bits to the beginning of the resulting
2171 /// Please note this isn't the same operation as `>>`!
2177 /// Please note that this example is shared between integer types.
2178 /// Which explains why `u64` is used here.
2181 /// let n = 0x0123456789ABCDEFu64;
2182 /// let m = 0xDEF0123456789ABCu64;
2184 /// assert_eq!(n.rotate_right(12), m);
2186 #[stable(feature = "rust1", since = "1.0.0")]
2188 pub fn rotate_right(self, n: u32) -> Self {
2189 // Protect against undefined behaviour for over-long bit shifts
2191 (self >> n) | (self << (($BITS - n) % $BITS))
2194 /// Reverses the byte order of the integer.
2200 /// Please note that this example is shared between integer types.
2201 /// Which explains why `u16` is used here.
2204 /// let n: u16 = 0b0000000_01010101;
2205 /// assert_eq!(n, 85);
2207 /// let m = n.swap_bytes();
2209 /// assert_eq!(m, 0b01010101_00000000);
2210 /// assert_eq!(m, 21760);
2212 #[stable(feature = "rust1", since = "1.0.0")]
2213 #[rustc_const_unstable(feature = "const_int_ops")]
2215 pub const fn swap_bytes(self) -> Self {
2216 unsafe { intrinsics::bswap(self as $ActualT) as Self }
2219 /// Reverses the bit pattern of the integer.
2225 /// Please note that this example is shared between integer types.
2226 /// Which explains why `u16` is used here.
2229 /// #![feature(reverse_bits)]
2231 /// let n: u16 = 0b0000000_01010101;
2232 /// assert_eq!(n, 85);
2234 /// let m = n.reverse_bits();
2236 /// assert_eq!(m, 0b10101010_00000000);
2237 /// assert_eq!(m, 43520);
2239 #[unstable(feature = "reverse_bits", issue = "48763")]
2241 pub fn reverse_bits(self) -> Self {
2242 unsafe { intrinsics::bitreverse(self as $ActualT) as Self }
2246 concat!("Converts an integer from big endian to the target's endianness.
2248 On big endian this is a no-op. On little endian the bytes are
2256 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2258 if cfg!(target_endian = \"big\") {
2259 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
2261 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
2264 #[stable(feature = "rust1", since = "1.0.0")]
2265 #[rustc_const_unstable(feature = "const_int_ops")]
2267 pub const fn from_be(x: Self) -> Self {
2268 #[cfg(target_endian = "big")]
2272 #[cfg(not(target_endian = "big"))]
2280 concat!("Converts an integer from little endian to the target's endianness.
2282 On little endian this is a no-op. On big endian the bytes are
2290 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2292 if cfg!(target_endian = \"little\") {
2293 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
2295 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
2298 #[stable(feature = "rust1", since = "1.0.0")]
2299 #[rustc_const_unstable(feature = "const_int_ops")]
2301 pub const fn from_le(x: Self) -> Self {
2302 #[cfg(target_endian = "little")]
2306 #[cfg(not(target_endian = "little"))]
2314 concat!("Converts `self` to big endian from the target's endianness.
2316 On big endian this is a no-op. On little endian the bytes are
2324 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2326 if cfg!(target_endian = \"big\") {
2327 assert_eq!(n.to_be(), n)
2329 assert_eq!(n.to_be(), n.swap_bytes())
2332 #[stable(feature = "rust1", since = "1.0.0")]
2333 #[rustc_const_unstable(feature = "const_int_ops")]
2335 pub const fn to_be(self) -> Self { // or not to be?
2336 #[cfg(target_endian = "big")]
2340 #[cfg(not(target_endian = "big"))]
2348 concat!("Converts `self` to little endian from the target's endianness.
2350 On little endian this is a no-op. On big endian the bytes are
2358 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2360 if cfg!(target_endian = \"little\") {
2361 assert_eq!(n.to_le(), n)
2363 assert_eq!(n.to_le(), n.swap_bytes())
2366 #[stable(feature = "rust1", since = "1.0.0")]
2367 #[rustc_const_unstable(feature = "const_int_ops")]
2369 pub const fn to_le(self) -> Self {
2370 #[cfg(target_endian = "little")]
2374 #[cfg(not(target_endian = "little"))]
2382 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2383 if overflow occurred.
2390 ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), ",
2391 "Some(", stringify!($SelfT), "::max_value() - 1));
2392 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);", $EndFeature, "
2394 #[stable(feature = "rust1", since = "1.0.0")]
2396 pub fn checked_add(self, rhs: Self) -> Option<Self> {
2397 let (a, b) = self.overflowing_add(rhs);
2398 if b {None} else {Some(a)}
2403 concat!("Checked integer subtraction. Computes `self - rhs`, returning
2404 `None` if overflow occurred.
2411 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
2412 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
2414 #[stable(feature = "rust1", since = "1.0.0")]
2416 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
2417 let (a, b) = self.overflowing_sub(rhs);
2418 if b {None} else {Some(a)}
2423 concat!("Checked integer multiplication. Computes `self * rhs`, returning
2424 `None` if overflow occurred.
2431 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
2432 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, "
2434 #[stable(feature = "rust1", since = "1.0.0")]
2436 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
2437 let (a, b) = self.overflowing_mul(rhs);
2438 if b {None} else {Some(a)}
2443 concat!("Checked integer division. Computes `self / rhs`, returning `None`
2451 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2452 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2454 #[stable(feature = "rust1", since = "1.0.0")]
2456 pub fn checked_div(self, rhs: Self) -> Option<Self> {
2459 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
2465 concat!("Checked Euclidean division. Computes `self.div_euc(rhs)`, returning `None`
2473 #![feature(euclidean_division)]
2474 assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2475 assert_eq!(1", stringify!($SelfT), ".checked_div_euc(0), None);
2477 #[unstable(feature = "euclidean_division", issue = "49048")]
2479 pub fn checked_div_euc(self, rhs: Self) -> Option<Self> {
2483 Some(self.div_euc(rhs))
2490 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
2498 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
2499 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
2501 #[stable(feature = "wrapping", since = "1.7.0")]
2503 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
2507 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
2513 concat!("Checked Euclidean modulo. Computes `self.mod_euc(rhs)`, returning `None`
2521 #![feature(euclidean_division)]
2522 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(2), Some(1));
2523 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(0), None);
2525 #[unstable(feature = "euclidean_division", issue = "49048")]
2527 pub fn checked_mod_euc(self, rhs: Self) -> Option<Self> {
2531 Some(self.mod_euc(rhs))
2537 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
2540 Note that negating any positive integer will overflow.
2547 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
2548 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
2550 #[stable(feature = "wrapping", since = "1.7.0")]
2552 pub fn checked_neg(self) -> Option<Self> {
2553 let (a, b) = self.overflowing_neg();
2554 if b {None} else {Some(a)}
2559 concat!("Checked shift left. Computes `self << rhs`, returning `None`
2560 if `rhs` is larger than or equal to the number of bits in `self`.
2567 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
2568 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
2570 #[stable(feature = "wrapping", since = "1.7.0")]
2572 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
2573 let (a, b) = self.overflowing_shl(rhs);
2574 if b {None} else {Some(a)}
2579 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
2580 if `rhs` is larger than or equal to the number of bits in `self`.
2587 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
2588 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
2590 #[stable(feature = "wrapping", since = "1.7.0")]
2592 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
2593 let (a, b) = self.overflowing_shr(rhs);
2594 if b {None} else {Some(a)}
2599 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
2607 #![feature(no_panic_pow)]
2608 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
2609 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, "
2611 #[unstable(feature = "no_panic_pow", issue = "48320")]
2613 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
2614 let mut base = self;
2615 let mut acc: Self = 1;
2619 acc = acc.checked_mul(base)?;
2622 base = base.checked_mul(base)?;
2625 // Deal with the final bit of the exponent separately, since
2626 // squaring the base afterwards is not necessary and may cause a
2627 // needless overflow.
2629 acc = acc.checked_mul(base)?;
2637 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
2638 the numeric bounds instead of overflowing.
2645 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
2646 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
2648 #[stable(feature = "rust1", since = "1.0.0")]
2650 pub fn saturating_add(self, rhs: Self) -> Self {
2651 match self.checked_add(rhs) {
2653 None => Self::max_value(),
2659 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
2660 at the numeric bounds instead of overflowing.
2667 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
2668 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
2670 #[stable(feature = "rust1", since = "1.0.0")]
2672 pub fn saturating_sub(self, rhs: Self) -> Self {
2673 match self.checked_sub(rhs) {
2675 None => Self::min_value(),
2681 concat!("Saturating integer multiplication. Computes `self * rhs`,
2682 saturating at the numeric bounds instead of overflowing.
2689 ", $Feature, "use std::", stringify!($SelfT), ";
2691 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
2692 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
2693 "::MAX);", $EndFeature, "
2695 #[stable(feature = "wrapping", since = "1.7.0")]
2697 pub fn saturating_mul(self, rhs: Self) -> Self {
2698 self.checked_mul(rhs).unwrap_or(Self::max_value())
2703 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
2704 saturating at the numeric bounds instead of overflowing.
2711 #![feature(no_panic_pow)]
2712 ", $Feature, "use std::", stringify!($SelfT), ";
2714 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
2715 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
2718 #[unstable(feature = "no_panic_pow", issue = "48320")]
2720 pub fn saturating_pow(self, exp: u32) -> Self {
2721 match self.checked_pow(exp) {
2723 None => Self::max_value(),
2729 concat!("Wrapping (modular) addition. Computes `self + rhs`,
2730 wrapping around at the boundary of the type.
2737 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
2738 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
2741 #[stable(feature = "rust1", since = "1.0.0")]
2743 pub fn wrapping_add(self, rhs: Self) -> Self {
2745 intrinsics::overflowing_add(self, rhs)
2751 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
2752 wrapping around at the boundary of the type.
2759 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
2760 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
2763 #[stable(feature = "rust1", since = "1.0.0")]
2765 pub fn wrapping_sub(self, rhs: Self) -> Self {
2767 intrinsics::overflowing_sub(self, rhs)
2772 /// Wrapping (modular) multiplication. Computes `self *
2773 /// rhs`, wrapping around at the boundary of the type.
2779 /// Please note that this example is shared between integer types.
2780 /// Which explains why `u8` is used here.
2783 /// assert_eq!(10u8.wrapping_mul(12), 120);
2784 /// assert_eq!(25u8.wrapping_mul(12), 44);
2786 #[stable(feature = "rust1", since = "1.0.0")]
2788 pub fn wrapping_mul(self, rhs: Self) -> Self {
2790 intrinsics::overflowing_mul(self, rhs)
2795 concat!("Wrapping (modular) division. Computes `self / rhs`.
2796 Wrapped division on unsigned types is just normal division.
2797 There's no way wrapping could ever happen.
2798 This function exists, so that all operations
2799 are accounted for in the wrapping operations.
2806 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
2808 #[stable(feature = "num_wrapping", since = "1.2.0")]
2810 pub fn wrapping_div(self, rhs: Self) -> Self {
2816 concat!("Wrapping Euclidean division. Computes `self.div_euc(rhs)`.
2817 Wrapped division on unsigned types is just normal division.
2818 There's no way wrapping could ever happen.
2819 This function exists, so that all operations
2820 are accounted for in the wrapping operations.
2827 #![feature(euclidean_division)]
2828 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euc(10), 10);
2830 #[unstable(feature = "euclidean_division", issue = "49048")]
2832 pub fn wrapping_div_euc(self, rhs: Self) -> Self {
2838 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
2839 Wrapped remainder calculation on unsigned types is
2840 just the regular remainder calculation.
2841 There's no way wrapping could ever happen.
2842 This function exists, so that all operations
2843 are accounted for in the wrapping operations.
2850 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
2852 #[stable(feature = "num_wrapping", since = "1.2.0")]
2854 pub fn wrapping_rem(self, rhs: Self) -> Self {
2860 concat!("Wrapping Euclidean modulo. Computes `self.mod_euc(rhs)`.
2861 Wrapped modulo calculation on unsigned types is
2862 just the regular remainder calculation.
2863 There's no way wrapping could ever happen.
2864 This function exists, so that all operations
2865 are accounted for in the wrapping operations.
2872 #![feature(euclidean_division)]
2873 assert_eq!(100", stringify!($SelfT), ".wrapping_mod_euc(10), 0);
2875 #[unstable(feature = "euclidean_division", issue = "49048")]
2877 pub fn wrapping_mod_euc(self, rhs: Self) -> Self {
2882 /// Wrapping (modular) negation. Computes `-self`,
2883 /// wrapping around at the boundary of the type.
2885 /// Since unsigned types do not have negative equivalents
2886 /// all applications of this function will wrap (except for `-0`).
2887 /// For values smaller than the corresponding signed type's maximum
2888 /// the result is the same as casting the corresponding signed value.
2889 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
2890 /// `MAX` is the corresponding signed type's maximum.
2896 /// Please note that this example is shared between integer types.
2897 /// Which explains why `i8` is used here.
2900 /// assert_eq!(100i8.wrapping_neg(), -100);
2901 /// assert_eq!((-128i8).wrapping_neg(), -128);
2903 #[stable(feature = "num_wrapping", since = "1.2.0")]
2905 pub fn wrapping_neg(self) -> Self {
2906 self.overflowing_neg().0
2910 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
2911 where `mask` removes any high-order bits of `rhs` that
2912 would cause the shift to exceed the bitwidth of the type.
2914 Note that this is *not* the same as a rotate-left; the
2915 RHS of a wrapping shift-left is restricted to the range
2916 of the type, rather than the bits shifted out of the LHS
2917 being returned to the other end. The primitive integer
2918 types all implement a `rotate_left` function, which may
2919 be what you want instead.
2926 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
2927 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
2929 #[stable(feature = "num_wrapping", since = "1.2.0")]
2931 pub fn wrapping_shl(self, rhs: u32) -> Self {
2933 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
2939 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
2940 where `mask` removes any high-order bits of `rhs` that
2941 would cause the shift to exceed the bitwidth of the type.
2943 Note that this is *not* the same as a rotate-right; the
2944 RHS of a wrapping shift-right is restricted to the range
2945 of the type, rather than the bits shifted out of the LHS
2946 being returned to the other end. The primitive integer
2947 types all implement a `rotate_right` function, which may
2948 be what you want instead.
2955 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
2956 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
2958 #[stable(feature = "num_wrapping", since = "1.2.0")]
2960 pub fn wrapping_shr(self, rhs: u32) -> Self {
2962 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
2968 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
2969 wrapping around at the boundary of the type.
2976 #![feature(no_panic_pow)]
2977 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
2978 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
2980 #[unstable(feature = "no_panic_pow", issue = "48320")]
2982 pub fn wrapping_pow(self, mut exp: u32) -> Self {
2983 let mut base = self;
2984 let mut acc: Self = 1;
2988 acc = acc.wrapping_mul(base);
2991 base = base.wrapping_mul(base);
2994 // Deal with the final bit of the exponent separately, since
2995 // squaring the base afterwards is not necessary and may cause a
2996 // needless overflow.
2998 acc = acc.wrapping_mul(base);
3006 concat!("Calculates `self` + `rhs`
3008 Returns a tuple of the addition along with a boolean indicating
3009 whether an arithmetic overflow would occur. If an overflow would
3010 have occurred then the wrapped value is returned.
3017 ", $Feature, "use std::", stringify!($SelfT), ";
3019 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
3020 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
3023 #[stable(feature = "wrapping", since = "1.7.0")]
3024 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
3025 let (a, b) = unsafe {
3026 intrinsics::add_with_overflow(self as $ActualT,
3034 concat!("Calculates `self` - `rhs`
3036 Returns a tuple of the subtraction along with a boolean indicating
3037 whether an arithmetic overflow would occur. If an overflow would
3038 have occurred then the wrapped value is returned.
3045 ", $Feature, "use std::", stringify!($SelfT), ";
3047 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
3048 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
3052 #[stable(feature = "wrapping", since = "1.7.0")]
3053 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3054 let (a, b) = unsafe {
3055 intrinsics::sub_with_overflow(self as $ActualT,
3062 /// Calculates the multiplication of `self` and `rhs`.
3064 /// Returns a tuple of the multiplication along with a boolean
3065 /// indicating whether an arithmetic overflow would occur. If an
3066 /// overflow would have occurred then the wrapped value is returned.
3072 /// Please note that this example is shared between integer types.
3073 /// Which explains why `u32` is used here.
3076 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3077 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3080 #[stable(feature = "wrapping", since = "1.7.0")]
3081 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3082 let (a, b) = unsafe {
3083 intrinsics::mul_with_overflow(self as $ActualT,
3090 concat!("Calculates the divisor when `self` is divided by `rhs`.
3092 Returns a tuple of the divisor along with a boolean indicating
3093 whether an arithmetic overflow would occur. Note that for unsigned
3094 integers overflow never occurs, so the second value is always
3099 This function will panic if `rhs` is 0.
3106 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
3109 #[stable(feature = "wrapping", since = "1.7.0")]
3110 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3116 concat!("Calculates the quotient of Euclidean division `self.div_euc(rhs)`.
3118 Returns a tuple of the divisor along with a boolean indicating
3119 whether an arithmetic overflow would occur. Note that for unsigned
3120 integers overflow never occurs, so the second value is always
3125 This function will panic if `rhs` is 0.
3132 #![feature(euclidean_division)]
3133 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euc(2), (2, false));
3136 #[unstable(feature = "euclidean_division", issue = "49048")]
3137 pub fn overflowing_div_euc(self, rhs: Self) -> (Self, bool) {
3143 concat!("Calculates the remainder when `self` is divided by `rhs`.
3145 Returns a tuple of the remainder after dividing along with a boolean
3146 indicating whether an arithmetic overflow would occur. Note that for
3147 unsigned integers overflow never occurs, so the second value is
3152 This function will panic if `rhs` is 0.
3159 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3162 #[stable(feature = "wrapping", since = "1.7.0")]
3163 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3169 concat!("Calculates the remainder `self.mod_euc(rhs)` by Euclidean division.
3171 Returns a tuple of the modulo after dividing along with a boolean
3172 indicating whether an arithmetic overflow would occur. Note that for
3173 unsigned integers overflow never occurs, so the second value is
3178 This function will panic if `rhs` is 0.
3185 #![feature(euclidean_division)]
3186 assert_eq!(5", stringify!($SelfT), ".overflowing_mod_euc(2), (1, false));
3189 #[unstable(feature = "euclidean_division", issue = "49048")]
3190 pub fn overflowing_mod_euc(self, rhs: Self) -> (Self, bool) {
3196 concat!("Negates self in an overflowing fashion.
3198 Returns `!self + 1` using wrapping operations to return the value
3199 that represents the negation of this unsigned value. Note that for
3200 positive unsigned values overflow always occurs, but negating 0 does
3208 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3209 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3210 ", true));", $EndFeature, "
3213 #[stable(feature = "wrapping", since = "1.7.0")]
3214 pub fn overflowing_neg(self) -> (Self, bool) {
3215 ((!self).wrapping_add(1), self != 0)
3220 concat!("Shifts self left by `rhs` bits.
3222 Returns a tuple of the shifted version of self along with a boolean
3223 indicating whether the shift value was larger than or equal to the
3224 number of bits. If the shift value is too large, then value is
3225 masked (N-1) where N is the number of bits, and this value is then
3226 used to perform the shift.
3233 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3234 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3237 #[stable(feature = "wrapping", since = "1.7.0")]
3238 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3239 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3244 concat!("Shifts self right by `rhs` bits.
3246 Returns a tuple of the shifted version of self along with a boolean
3247 indicating whether the shift value was larger than or equal to the
3248 number of bits. If the shift value is too large, then value is
3249 masked (N-1) where N is the number of bits, and this value is then
3250 used to perform the shift.
3257 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
3258 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
3261 #[stable(feature = "wrapping", since = "1.7.0")]
3262 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3263 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
3268 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3270 Returns a tuple of the exponentiation along with a bool indicating
3271 whether an overflow happened.
3278 #![feature(no_panic_pow)]
3279 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
3280 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
3282 #[unstable(feature = "no_panic_pow", issue = "48320")]
3284 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3285 let mut base = self;
3286 let mut acc: Self = 1;
3287 let mut overflown = false;
3288 // Scratch space for storing results of overflowing_mul.
3293 r = acc.overflowing_mul(base);
3298 r = base.overflowing_mul(base);
3303 // Deal with the final bit of the exponent separately, since
3304 // squaring the base afterwards is not necessary and may cause a
3305 // needless overflow.
3307 r = acc.overflowing_mul(base);
3317 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3324 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
3326 #[stable(feature = "rust1", since = "1.0.0")]
3328 #[rustc_inherit_overflow_checks]
3329 pub fn pow(self, mut exp: u32) -> Self {
3330 let mut base = self;
3341 // Deal with the final bit of the exponent separately, since
3342 // squaring the base afterwards is not necessary and may cause a
3343 // needless overflow.
3353 concat!("Performs Euclidean division.
3355 For unsigned types, this is just the same as `self / rhs`.
3362 #![feature(euclidean_division)]
3363 assert_eq!(7", stringify!($SelfT), ".div_euc(4), 1); // or any other integer type
3365 #[unstable(feature = "euclidean_division", issue = "49048")]
3367 #[rustc_inherit_overflow_checks]
3368 pub fn div_euc(self, rhs: Self) -> Self {
3375 concat!("Calculates the remainder `self mod rhs` by Euclidean division.
3377 For unsigned types, this is just the same as `self % rhs`.
3384 #![feature(euclidean_division)]
3385 assert_eq!(7", stringify!($SelfT), ".mod_euc(4), 3); // or any other integer type
3387 #[unstable(feature = "euclidean_division", issue = "49048")]
3389 #[rustc_inherit_overflow_checks]
3390 pub fn mod_euc(self, rhs: Self) -> Self {
3396 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
3403 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
3404 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
3406 #[stable(feature = "rust1", since = "1.0.0")]
3408 pub fn is_power_of_two(self) -> bool {
3409 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
3413 // Returns one less than next power of two.
3414 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
3416 // 8u8.one_less_than_next_power_of_two() == 7
3417 // 6u8.one_less_than_next_power_of_two() == 7
3419 // This method cannot overflow, as in the `next_power_of_two`
3420 // overflow cases it instead ends up returning the maximum value
3421 // of the type, and can return 0 for 0.
3423 fn one_less_than_next_power_of_two(self) -> Self {
3424 if self <= 1 { return 0; }
3426 // Because `p > 0`, it cannot consist entirely of leading zeros.
3427 // That means the shift is always in-bounds, and some processors
3428 // (such as intel pre-haswell) have more efficient ctlz
3429 // intrinsics when the argument is non-zero.
3431 let z = unsafe { intrinsics::ctlz_nonzero(p) };
3432 <$SelfT>::max_value() >> z
3436 concat!("Returns the smallest power of two greater than or equal to `self`.
3438 When return value overflows (i.e. `self > (1 << (N-1))` for type
3439 `uN`), it panics in debug mode and return value is wrapped to 0 in
3440 release mode (the only situation in which method can return 0).
3447 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
3448 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
3450 #[stable(feature = "rust1", since = "1.0.0")]
3452 pub fn next_power_of_two(self) -> Self {
3453 // Call the trait to get overflow checks
3454 ops::Add::add(self.one_less_than_next_power_of_two(), 1)
3459 concat!("Returns the smallest power of two greater than or equal to `n`. If
3460 the next power of two is greater than the type's maximum value,
3461 `None` is returned, otherwise the power of two is wrapped in `Some`.
3468 ", $Feature, "assert_eq!(2", stringify!($SelfT),
3469 ".checked_next_power_of_two(), Some(2));
3470 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
3471 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
3474 #[stable(feature = "rust1", since = "1.0.0")]
3475 pub fn checked_next_power_of_two(self) -> Option<Self> {
3476 self.one_less_than_next_power_of_two().checked_add(1)
3481 concat!("Returns the smallest power of two greater than or equal to `n`. If
3482 the next power of two is greater than the type's maximum value,
3483 the return value is wrapped to `0`.
3490 #![feature(wrapping_next_power_of_two)]
3492 assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);
3493 assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);
3494 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_next_power_of_two(), 0);",
3497 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
3498 reason = "needs decision on wrapping behaviour")]
3499 pub fn wrapping_next_power_of_two(self) -> Self {
3500 self.one_less_than_next_power_of_two().wrapping_add(1)
3504 /// Return the memory representation of this integer as a byte array.
3506 /// The target platform’s native endianness is used.
3507 /// Portable code likely wants to use this after [`to_be`] or [`to_le`].
3509 /// [`to_be`]: #method.to_be
3510 /// [`to_le`]: #method.to_le
3515 /// #![feature(int_to_from_bytes)]
3517 /// let bytes = 0x1234_5678_u32.to_be().to_bytes();
3518 /// assert_eq!(bytes, [0x12, 0x34, 0x56, 0x78]);
3520 #[unstable(feature = "int_to_from_bytes", issue = "49792")]
3522 pub fn to_bytes(self) -> [u8; mem::size_of::<Self>()] {
3523 unsafe { mem::transmute(self) }
3526 /// Create an integer value from its memory representation as a byte array.
3528 /// The target platform’s native endianness is used.
3529 /// Portable code likely wants to use [`to_be`] or [`to_le`] after this.
3531 /// [`to_be`]: #method.to_be
3532 /// [`to_le`]: #method.to_le
3537 /// #![feature(int_to_from_bytes)]
3539 /// let int = u32::from_be(u32::from_bytes([0x12, 0x34, 0x56, 0x78]));
3540 /// assert_eq!(int, 0x1234_5678_u32);
3542 #[unstable(feature = "int_to_from_bytes", issue = "49792")]
3544 pub fn from_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3545 unsafe { mem::transmute(bytes) }
3552 uint_impl! { u8, u8, 8, 255, "", "" }
3555 /// Checks if the value is within the ASCII range.
3560 /// let ascii = 97u8;
3561 /// let non_ascii = 150u8;
3563 /// assert!(ascii.is_ascii());
3564 /// assert!(!non_ascii.is_ascii());
3566 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3568 pub fn is_ascii(&self) -> bool {
3572 /// Makes a copy of the value in its ASCII upper case equivalent.
3574 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3575 /// but non-ASCII letters are unchanged.
3577 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
3582 /// let lowercase_a = 97u8;
3584 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
3587 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
3588 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3590 pub fn to_ascii_uppercase(&self) -> u8 {
3591 ASCII_UPPERCASE_MAP[*self as usize]
3594 /// Makes a copy of the value in its ASCII lower case equivalent.
3596 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3597 /// but non-ASCII letters are unchanged.
3599 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
3604 /// let uppercase_a = 65u8;
3606 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
3609 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
3610 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3612 pub fn to_ascii_lowercase(&self) -> u8 {
3613 ASCII_LOWERCASE_MAP[*self as usize]
3616 /// Checks that two values are an ASCII case-insensitive match.
3618 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
3623 /// let lowercase_a = 97u8;
3624 /// let uppercase_a = 65u8;
3626 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
3628 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3630 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
3631 self.to_ascii_lowercase() == other.to_ascii_lowercase()
3634 /// Converts this value to its ASCII upper case equivalent in-place.
3636 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3637 /// but non-ASCII letters are unchanged.
3639 /// To return a new uppercased value without modifying the existing one, use
3640 /// [`to_ascii_uppercase`].
3645 /// let mut byte = b'a';
3647 /// byte.make_ascii_uppercase();
3649 /// assert_eq!(b'A', byte);
3652 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
3653 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3655 pub fn make_ascii_uppercase(&mut self) {
3656 *self = self.to_ascii_uppercase();
3659 /// Converts this value to its ASCII lower case equivalent in-place.
3661 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3662 /// but non-ASCII letters are unchanged.
3664 /// To return a new lowercased value without modifying the existing one, use
3665 /// [`to_ascii_lowercase`].
3670 /// let mut byte = b'A';
3672 /// byte.make_ascii_lowercase();
3674 /// assert_eq!(b'a', byte);
3677 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
3678 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3680 pub fn make_ascii_lowercase(&mut self) {
3681 *self = self.to_ascii_lowercase();
3684 /// Checks if the value is an ASCII alphabetic character:
3686 /// - U+0041 'A' ... U+005A 'Z', or
3687 /// - U+0061 'a' ... U+007A 'z'.
3692 /// #![feature(ascii_ctype)]
3694 /// let uppercase_a = b'A';
3695 /// let uppercase_g = b'G';
3698 /// let zero = b'0';
3699 /// let percent = b'%';
3700 /// let space = b' ';
3702 /// let esc = 0x1b_u8;
3704 /// assert!(uppercase_a.is_ascii_alphabetic());
3705 /// assert!(uppercase_g.is_ascii_alphabetic());
3706 /// assert!(a.is_ascii_alphabetic());
3707 /// assert!(g.is_ascii_alphabetic());
3708 /// assert!(!zero.is_ascii_alphabetic());
3709 /// assert!(!percent.is_ascii_alphabetic());
3710 /// assert!(!space.is_ascii_alphabetic());
3711 /// assert!(!lf.is_ascii_alphabetic());
3712 /// assert!(!esc.is_ascii_alphabetic());
3714 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3716 pub fn is_ascii_alphabetic(&self) -> bool {
3717 if *self >= 0x80 { return false; }
3718 match ASCII_CHARACTER_CLASS[*self as usize] {
3719 L | Lx | U | Ux => true,
3724 /// Checks if the value is an ASCII uppercase character:
3725 /// U+0041 'A' ... U+005A 'Z'.
3730 /// #![feature(ascii_ctype)]
3732 /// let uppercase_a = b'A';
3733 /// let uppercase_g = b'G';
3736 /// let zero = b'0';
3737 /// let percent = b'%';
3738 /// let space = b' ';
3740 /// let esc = 0x1b_u8;
3742 /// assert!(uppercase_a.is_ascii_uppercase());
3743 /// assert!(uppercase_g.is_ascii_uppercase());
3744 /// assert!(!a.is_ascii_uppercase());
3745 /// assert!(!g.is_ascii_uppercase());
3746 /// assert!(!zero.is_ascii_uppercase());
3747 /// assert!(!percent.is_ascii_uppercase());
3748 /// assert!(!space.is_ascii_uppercase());
3749 /// assert!(!lf.is_ascii_uppercase());
3750 /// assert!(!esc.is_ascii_uppercase());
3752 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3754 pub fn is_ascii_uppercase(&self) -> bool {
3755 if *self >= 0x80 { return false }
3756 match ASCII_CHARACTER_CLASS[*self as usize] {
3762 /// Checks if the value is an ASCII lowercase character:
3763 /// U+0061 'a' ... U+007A 'z'.
3768 /// #![feature(ascii_ctype)]
3770 /// let uppercase_a = b'A';
3771 /// let uppercase_g = b'G';
3774 /// let zero = b'0';
3775 /// let percent = b'%';
3776 /// let space = b' ';
3778 /// let esc = 0x1b_u8;
3780 /// assert!(!uppercase_a.is_ascii_lowercase());
3781 /// assert!(!uppercase_g.is_ascii_lowercase());
3782 /// assert!(a.is_ascii_lowercase());
3783 /// assert!(g.is_ascii_lowercase());
3784 /// assert!(!zero.is_ascii_lowercase());
3785 /// assert!(!percent.is_ascii_lowercase());
3786 /// assert!(!space.is_ascii_lowercase());
3787 /// assert!(!lf.is_ascii_lowercase());
3788 /// assert!(!esc.is_ascii_lowercase());
3790 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3792 pub fn is_ascii_lowercase(&self) -> bool {
3793 if *self >= 0x80 { return false }
3794 match ASCII_CHARACTER_CLASS[*self as usize] {
3800 /// Checks if the value is an ASCII alphanumeric character:
3802 /// - U+0041 'A' ... U+005A 'Z', or
3803 /// - U+0061 'a' ... U+007A 'z', or
3804 /// - U+0030 '0' ... U+0039 '9'.
3809 /// #![feature(ascii_ctype)]
3811 /// let uppercase_a = b'A';
3812 /// let uppercase_g = b'G';
3815 /// let zero = b'0';
3816 /// let percent = b'%';
3817 /// let space = b' ';
3819 /// let esc = 0x1b_u8;
3821 /// assert!(uppercase_a.is_ascii_alphanumeric());
3822 /// assert!(uppercase_g.is_ascii_alphanumeric());
3823 /// assert!(a.is_ascii_alphanumeric());
3824 /// assert!(g.is_ascii_alphanumeric());
3825 /// assert!(zero.is_ascii_alphanumeric());
3826 /// assert!(!percent.is_ascii_alphanumeric());
3827 /// assert!(!space.is_ascii_alphanumeric());
3828 /// assert!(!lf.is_ascii_alphanumeric());
3829 /// assert!(!esc.is_ascii_alphanumeric());
3831 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3833 pub fn is_ascii_alphanumeric(&self) -> bool {
3834 if *self >= 0x80 { return false }
3835 match ASCII_CHARACTER_CLASS[*self as usize] {
3836 D | L | Lx | U | Ux => true,
3841 /// Checks if the value is an ASCII decimal digit:
3842 /// U+0030 '0' ... U+0039 '9'.
3847 /// #![feature(ascii_ctype)]
3849 /// let uppercase_a = b'A';
3850 /// let uppercase_g = b'G';
3853 /// let zero = b'0';
3854 /// let percent = b'%';
3855 /// let space = b' ';
3857 /// let esc = 0x1b_u8;
3859 /// assert!(!uppercase_a.is_ascii_digit());
3860 /// assert!(!uppercase_g.is_ascii_digit());
3861 /// assert!(!a.is_ascii_digit());
3862 /// assert!(!g.is_ascii_digit());
3863 /// assert!(zero.is_ascii_digit());
3864 /// assert!(!percent.is_ascii_digit());
3865 /// assert!(!space.is_ascii_digit());
3866 /// assert!(!lf.is_ascii_digit());
3867 /// assert!(!esc.is_ascii_digit());
3869 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3871 pub fn is_ascii_digit(&self) -> bool {
3872 if *self >= 0x80 { return false }
3873 match ASCII_CHARACTER_CLASS[*self as usize] {
3879 /// Checks if the value is an ASCII hexadecimal digit:
3881 /// - U+0030 '0' ... U+0039 '9', or
3882 /// - U+0041 'A' ... U+0046 'F', or
3883 /// - U+0061 'a' ... U+0066 'f'.
3888 /// #![feature(ascii_ctype)]
3890 /// let uppercase_a = b'A';
3891 /// let uppercase_g = b'G';
3894 /// let zero = b'0';
3895 /// let percent = b'%';
3896 /// let space = b' ';
3898 /// let esc = 0x1b_u8;
3900 /// assert!(uppercase_a.is_ascii_hexdigit());
3901 /// assert!(!uppercase_g.is_ascii_hexdigit());
3902 /// assert!(a.is_ascii_hexdigit());
3903 /// assert!(!g.is_ascii_hexdigit());
3904 /// assert!(zero.is_ascii_hexdigit());
3905 /// assert!(!percent.is_ascii_hexdigit());
3906 /// assert!(!space.is_ascii_hexdigit());
3907 /// assert!(!lf.is_ascii_hexdigit());
3908 /// assert!(!esc.is_ascii_hexdigit());
3910 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3912 pub fn is_ascii_hexdigit(&self) -> bool {
3913 if *self >= 0x80 { return false }
3914 match ASCII_CHARACTER_CLASS[*self as usize] {
3915 D | Lx | Ux => true,
3920 /// Checks if the value is an ASCII punctuation character:
3922 /// - U+0021 ... U+002F `! " # $ % & ' ( ) * + , - . /`, or
3923 /// - U+003A ... U+0040 `: ; < = > ? @`, or
3924 /// - U+005B ... U+0060 ``[ \ ] ^ _ ` ``, or
3925 /// - U+007B ... U+007E `{ | } ~`
3930 /// #![feature(ascii_ctype)]
3932 /// let uppercase_a = b'A';
3933 /// let uppercase_g = b'G';
3936 /// let zero = b'0';
3937 /// let percent = b'%';
3938 /// let space = b' ';
3940 /// let esc = 0x1b_u8;
3942 /// assert!(!uppercase_a.is_ascii_punctuation());
3943 /// assert!(!uppercase_g.is_ascii_punctuation());
3944 /// assert!(!a.is_ascii_punctuation());
3945 /// assert!(!g.is_ascii_punctuation());
3946 /// assert!(!zero.is_ascii_punctuation());
3947 /// assert!(percent.is_ascii_punctuation());
3948 /// assert!(!space.is_ascii_punctuation());
3949 /// assert!(!lf.is_ascii_punctuation());
3950 /// assert!(!esc.is_ascii_punctuation());
3952 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3954 pub fn is_ascii_punctuation(&self) -> bool {
3955 if *self >= 0x80 { return false }
3956 match ASCII_CHARACTER_CLASS[*self as usize] {
3962 /// Checks if the value is an ASCII graphic character:
3963 /// U+0021 '!' ... U+007E '~'.
3968 /// #![feature(ascii_ctype)]
3970 /// let uppercase_a = b'A';
3971 /// let uppercase_g = b'G';
3974 /// let zero = b'0';
3975 /// let percent = b'%';
3976 /// let space = b' ';
3978 /// let esc = 0x1b_u8;
3980 /// assert!(uppercase_a.is_ascii_graphic());
3981 /// assert!(uppercase_g.is_ascii_graphic());
3982 /// assert!(a.is_ascii_graphic());
3983 /// assert!(g.is_ascii_graphic());
3984 /// assert!(zero.is_ascii_graphic());
3985 /// assert!(percent.is_ascii_graphic());
3986 /// assert!(!space.is_ascii_graphic());
3987 /// assert!(!lf.is_ascii_graphic());
3988 /// assert!(!esc.is_ascii_graphic());
3990 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3992 pub fn is_ascii_graphic(&self) -> bool {
3993 if *self >= 0x80 { return false; }
3994 match ASCII_CHARACTER_CLASS[*self as usize] {
3995 Ux | U | Lx | L | D | P => true,
4000 /// Checks if the value is an ASCII whitespace character:
4001 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
4002 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
4004 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
4005 /// whitespace][infra-aw]. There are several other definitions in
4006 /// wide use. For instance, [the POSIX locale][pct] includes
4007 /// U+000B VERTICAL TAB as well as all the above characters,
4008 /// but—from the very same specification—[the default rule for
4009 /// "field splitting" in the Bourne shell][bfs] considers *only*
4010 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
4012 /// If you are writing a program that will process an existing
4013 /// file format, check what that format's definition of whitespace is
4014 /// before using this function.
4016 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
4017 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
4018 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
4023 /// #![feature(ascii_ctype)]
4025 /// let uppercase_a = b'A';
4026 /// let uppercase_g = b'G';
4029 /// let zero = b'0';
4030 /// let percent = b'%';
4031 /// let space = b' ';
4033 /// let esc = 0x1b_u8;
4035 /// assert!(!uppercase_a.is_ascii_whitespace());
4036 /// assert!(!uppercase_g.is_ascii_whitespace());
4037 /// assert!(!a.is_ascii_whitespace());
4038 /// assert!(!g.is_ascii_whitespace());
4039 /// assert!(!zero.is_ascii_whitespace());
4040 /// assert!(!percent.is_ascii_whitespace());
4041 /// assert!(space.is_ascii_whitespace());
4042 /// assert!(lf.is_ascii_whitespace());
4043 /// assert!(!esc.is_ascii_whitespace());
4045 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4047 pub fn is_ascii_whitespace(&self) -> bool {
4048 if *self >= 0x80 { return false; }
4049 match ASCII_CHARACTER_CLASS[*self as usize] {
4055 /// Checks if the value is an ASCII control character:
4056 /// U+0000 NUL ... U+001F UNIT SEPARATOR, or U+007F DELETE.
4057 /// Note that most ASCII whitespace characters are control
4058 /// characters, but SPACE is not.
4063 /// #![feature(ascii_ctype)]
4065 /// let uppercase_a = b'A';
4066 /// let uppercase_g = b'G';
4069 /// let zero = b'0';
4070 /// let percent = b'%';
4071 /// let space = b' ';
4073 /// let esc = 0x1b_u8;
4075 /// assert!(!uppercase_a.is_ascii_control());
4076 /// assert!(!uppercase_g.is_ascii_control());
4077 /// assert!(!a.is_ascii_control());
4078 /// assert!(!g.is_ascii_control());
4079 /// assert!(!zero.is_ascii_control());
4080 /// assert!(!percent.is_ascii_control());
4081 /// assert!(!space.is_ascii_control());
4082 /// assert!(lf.is_ascii_control());
4083 /// assert!(esc.is_ascii_control());
4085 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4087 pub fn is_ascii_control(&self) -> bool {
4088 if *self >= 0x80 { return false; }
4089 match ASCII_CHARACTER_CLASS[*self as usize] {
4098 uint_impl! { u16, u16, 16, 65535, "", "" }
4103 uint_impl! { u32, u32, 32, 4294967295, "", "" }
4108 uint_impl! { u64, u64, 64, 18446744073709551615, "", "" }
4113 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "" }
4116 #[cfg(target_pointer_width = "16")]
4119 uint_impl! { usize, u16, 16, 65536, "", "" }
4121 #[cfg(target_pointer_width = "32")]
4124 uint_impl! { usize, u32, 32, 4294967295, "", "" }
4127 #[cfg(target_pointer_width = "64")]
4130 uint_impl! { usize, u64, 64, 18446744073709551615, "", "" }
4133 /// A classification of floating point numbers.
4135 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
4136 /// their documentation for more.
4138 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
4139 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
4144 /// use std::num::FpCategory;
4147 /// let num = 12.4_f32;
4148 /// let inf = f32::INFINITY;
4149 /// let zero = 0f32;
4150 /// let sub: f32 = 1.1754942e-38;
4151 /// let nan = f32::NAN;
4153 /// assert_eq!(num.classify(), FpCategory::Normal);
4154 /// assert_eq!(inf.classify(), FpCategory::Infinite);
4155 /// assert_eq!(zero.classify(), FpCategory::Zero);
4156 /// assert_eq!(nan.classify(), FpCategory::Nan);
4157 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
4159 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
4160 #[stable(feature = "rust1", since = "1.0.0")]
4161 pub enum FpCategory {
4162 /// "Not a Number", often obtained by dividing by zero.
4163 #[stable(feature = "rust1", since = "1.0.0")]
4166 /// Positive or negative infinity.
4167 #[stable(feature = "rust1", since = "1.0.0")]
4170 /// Positive or negative zero.
4171 #[stable(feature = "rust1", since = "1.0.0")]
4174 /// De-normalized floating point representation (less precise than `Normal`).
4175 #[stable(feature = "rust1", since = "1.0.0")]
4178 /// A regular floating point number.
4179 #[stable(feature = "rust1", since = "1.0.0")]
4183 macro_rules! from_str_radix_int_impl {
4185 #[stable(feature = "rust1", since = "1.0.0")]
4186 impl FromStr for $t {
4187 type Err = ParseIntError;
4188 fn from_str(src: &str) -> Result<Self, ParseIntError> {
4189 from_str_radix(src, 10)
4194 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
4196 /// The error type returned when a checked integral type conversion fails.
4197 #[unstable(feature = "try_from", issue = "33417")]
4198 #[derive(Debug, Copy, Clone)]
4199 pub struct TryFromIntError(());
4201 impl TryFromIntError {
4202 #[unstable(feature = "int_error_internals",
4203 reason = "available through Error trait and this method should \
4204 not be exposed publicly",
4207 pub fn __description(&self) -> &str {
4208 "out of range integral type conversion attempted"
4212 #[unstable(feature = "try_from", issue = "33417")]
4213 impl fmt::Display for TryFromIntError {
4214 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4215 self.__description().fmt(fmt)
4219 #[unstable(feature = "try_from", issue = "33417")]
4220 impl From<!> for TryFromIntError {
4221 fn from(never: !) -> TryFromIntError {
4226 // no possible bounds violation
4227 macro_rules! try_from_unbounded {
4228 ($source:ty, $($target:ty),*) => {$(
4229 #[unstable(feature = "try_from", issue = "33417")]
4230 impl TryFrom<$source> for $target {
4231 type Error = TryFromIntError;
4234 fn try_from(value: $source) -> Result<Self, Self::Error> {
4235 Ok(value as $target)
4241 // only negative bounds
4242 macro_rules! try_from_lower_bounded {
4243 ($source:ty, $($target:ty),*) => {$(
4244 #[unstable(feature = "try_from", issue = "33417")]
4245 impl TryFrom<$source> for $target {
4246 type Error = TryFromIntError;
4249 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4253 Err(TryFromIntError(()))
4260 // unsigned to signed (only positive bound)
4261 macro_rules! try_from_upper_bounded {
4262 ($source:ty, $($target:ty),*) => {$(
4263 #[unstable(feature = "try_from", issue = "33417")]
4264 impl TryFrom<$source> for $target {
4265 type Error = TryFromIntError;
4268 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4269 if u > (<$target>::max_value() as $source) {
4270 Err(TryFromIntError(()))
4280 macro_rules! try_from_both_bounded {
4281 ($source:ty, $($target:ty),*) => {$(
4282 #[unstable(feature = "try_from", issue = "33417")]
4283 impl TryFrom<$source> for $target {
4284 type Error = TryFromIntError;
4287 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4288 let min = <$target>::min_value() as $source;
4289 let max = <$target>::max_value() as $source;
4290 if u < min || u > max {
4291 Err(TryFromIntError(()))
4301 ($mac:ident, $source:ty, $($target:ty),*) => {$(
4302 $mac!($target, $source);
4306 /// intra-sign conversions
4307 try_from_upper_bounded!(u16, u8);
4308 try_from_upper_bounded!(u32, u16, u8);
4309 try_from_upper_bounded!(u64, u32, u16, u8);
4310 try_from_upper_bounded!(u128, u64, u32, u16, u8);
4312 try_from_both_bounded!(i16, i8);
4313 try_from_both_bounded!(i32, i16, i8);
4314 try_from_both_bounded!(i64, i32, i16, i8);
4315 try_from_both_bounded!(i128, i64, i32, i16, i8);
4317 // unsigned-to-signed
4318 try_from_upper_bounded!(u8, i8);
4319 try_from_upper_bounded!(u16, i8, i16);
4320 try_from_upper_bounded!(u32, i8, i16, i32);
4321 try_from_upper_bounded!(u64, i8, i16, i32, i64);
4322 try_from_upper_bounded!(u128, i8, i16, i32, i64, i128);
4324 // signed-to-unsigned
4325 try_from_lower_bounded!(i8, u8, u16, u32, u64, u128);
4326 try_from_lower_bounded!(i16, u16, u32, u64, u128);
4327 try_from_lower_bounded!(i32, u32, u64, u128);
4328 try_from_lower_bounded!(i64, u64, u128);
4329 try_from_lower_bounded!(i128, u128);
4330 try_from_both_bounded!(i16, u8);
4331 try_from_both_bounded!(i32, u16, u8);
4332 try_from_both_bounded!(i64, u32, u16, u8);
4333 try_from_both_bounded!(i128, u64, u32, u16, u8);
4336 try_from_upper_bounded!(usize, isize);
4337 try_from_lower_bounded!(isize, usize);
4339 #[cfg(target_pointer_width = "16")]
4340 mod ptr_try_from_impls {
4341 use super::TryFromIntError;
4342 use convert::TryFrom;
4344 try_from_upper_bounded!(usize, u8);
4345 try_from_unbounded!(usize, u16, u32, u64, u128);
4346 try_from_upper_bounded!(usize, i8, i16);
4347 try_from_unbounded!(usize, i32, i64, i128);
4349 try_from_both_bounded!(isize, u8);
4350 try_from_lower_bounded!(isize, u16, u32, u64, u128);
4351 try_from_both_bounded!(isize, i8);
4352 try_from_unbounded!(isize, i16, i32, i64, i128);
4354 rev!(try_from_upper_bounded, usize, u32, u64, u128);
4355 rev!(try_from_lower_bounded, usize, i8, i16);
4356 rev!(try_from_both_bounded, usize, i32, i64, i128);
4358 rev!(try_from_upper_bounded, isize, u16, u32, u64, u128);
4359 rev!(try_from_both_bounded, isize, i32, i64, i128);
4362 #[cfg(target_pointer_width = "32")]
4363 mod ptr_try_from_impls {
4364 use super::TryFromIntError;
4365 use convert::TryFrom;
4367 try_from_upper_bounded!(usize, u8, u16);
4368 try_from_unbounded!(usize, u32, u64, u128);
4369 try_from_upper_bounded!(usize, i8, i16, i32);
4370 try_from_unbounded!(usize, i64, i128);
4372 try_from_both_bounded!(isize, u8, u16);
4373 try_from_lower_bounded!(isize, u32, u64, u128);
4374 try_from_both_bounded!(isize, i8, i16);
4375 try_from_unbounded!(isize, i32, i64, i128);
4377 rev!(try_from_unbounded, usize, u32);
4378 rev!(try_from_upper_bounded, usize, u64, u128);
4379 rev!(try_from_lower_bounded, usize, i8, i16, i32);
4380 rev!(try_from_both_bounded, usize, i64, i128);
4382 rev!(try_from_unbounded, isize, u16);
4383 rev!(try_from_upper_bounded, isize, u32, u64, u128);
4384 rev!(try_from_unbounded, isize, i32);
4385 rev!(try_from_both_bounded, isize, i64, i128);
4388 #[cfg(target_pointer_width = "64")]
4389 mod ptr_try_from_impls {
4390 use super::TryFromIntError;
4391 use convert::TryFrom;
4393 try_from_upper_bounded!(usize, u8, u16, u32);
4394 try_from_unbounded!(usize, u64, u128);
4395 try_from_upper_bounded!(usize, i8, i16, i32, i64);
4396 try_from_unbounded!(usize, i128);
4398 try_from_both_bounded!(isize, u8, u16, u32);
4399 try_from_lower_bounded!(isize, u64, u128);
4400 try_from_both_bounded!(isize, i8, i16, i32);
4401 try_from_unbounded!(isize, i64, i128);
4403 rev!(try_from_unbounded, usize, u32, u64);
4404 rev!(try_from_upper_bounded, usize, u128);
4405 rev!(try_from_lower_bounded, usize, i8, i16, i32, i64);
4406 rev!(try_from_both_bounded, usize, i128);
4408 rev!(try_from_unbounded, isize, u16, u32);
4409 rev!(try_from_upper_bounded, isize, u64, u128);
4410 rev!(try_from_unbounded, isize, i32, i64);
4411 rev!(try_from_both_bounded, isize, i128);
4415 trait FromStrRadixHelper: PartialOrd + Copy {
4416 fn min_value() -> Self;
4417 fn max_value() -> Self;
4418 fn from_u32(u: u32) -> Self;
4419 fn checked_mul(&self, other: u32) -> Option<Self>;
4420 fn checked_sub(&self, other: u32) -> Option<Self>;
4421 fn checked_add(&self, other: u32) -> Option<Self>;
4425 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
4427 fn min_value() -> Self { Self::min_value() }
4429 fn max_value() -> Self { Self::max_value() }
4431 fn from_u32(u: u32) -> Self { u as Self }
4433 fn checked_mul(&self, other: u32) -> Option<Self> {
4434 Self::checked_mul(*self, other as Self)
4437 fn checked_sub(&self, other: u32) -> Option<Self> {
4438 Self::checked_sub(*self, other as Self)
4441 fn checked_add(&self, other: u32) -> Option<Self> {
4442 Self::checked_add(*self, other as Self)
4446 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
4448 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
4449 use self::IntErrorKind::*;
4450 use self::ParseIntError as PIE;
4452 assert!(radix >= 2 && radix <= 36,
4453 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
4457 return Err(PIE { kind: Empty });
4460 let is_signed_ty = T::from_u32(0) > T::min_value();
4462 // all valid digits are ascii, so we will just iterate over the utf8 bytes
4463 // and cast them to chars. .to_digit() will safely return None for anything
4464 // other than a valid ascii digit for the given radix, including the first-byte
4465 // of multi-byte sequences
4466 let src = src.as_bytes();
4468 let (is_positive, digits) = match src[0] {
4469 b'+' => (true, &src[1..]),
4470 b'-' if is_signed_ty => (false, &src[1..]),
4474 if digits.is_empty() {
4475 return Err(PIE { kind: Empty });
4478 let mut result = T::from_u32(0);
4480 // The number is positive
4482 let x = match (c as char).to_digit(radix) {
4484 None => return Err(PIE { kind: InvalidDigit }),
4486 result = match result.checked_mul(radix) {
4487 Some(result) => result,
4488 None => return Err(PIE { kind: Overflow }),
4490 result = match result.checked_add(x) {
4491 Some(result) => result,
4492 None => return Err(PIE { kind: Overflow }),
4496 // The number is negative
4498 let x = match (c as char).to_digit(radix) {
4500 None => return Err(PIE { kind: InvalidDigit }),
4502 result = match result.checked_mul(radix) {
4503 Some(result) => result,
4504 None => return Err(PIE { kind: Underflow }),
4506 result = match result.checked_sub(x) {
4507 Some(result) => result,
4508 None => return Err(PIE { kind: Underflow }),
4515 /// An error which can be returned when parsing an integer.
4517 /// This error is used as the error type for the `from_str_radix()` functions
4518 /// on the primitive integer types, such as [`i8::from_str_radix`].
4520 /// # Potential causes
4522 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
4523 /// in the string e.g. when it is obtained from the standard input.
4524 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
4526 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
4527 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
4528 #[derive(Debug, Clone, PartialEq, Eq)]
4529 #[stable(feature = "rust1", since = "1.0.0")]
4530 pub struct ParseIntError {
4534 #[derive(Debug, Clone, PartialEq, Eq)]
4542 impl ParseIntError {
4543 #[unstable(feature = "int_error_internals",
4544 reason = "available through Error trait and this method should \
4545 not be exposed publicly",
4548 pub fn __description(&self) -> &str {
4550 IntErrorKind::Empty => "cannot parse integer from empty string",
4551 IntErrorKind::InvalidDigit => "invalid digit found in string",
4552 IntErrorKind::Overflow => "number too large to fit in target type",
4553 IntErrorKind::Underflow => "number too small to fit in target type",
4558 #[stable(feature = "rust1", since = "1.0.0")]
4559 impl fmt::Display for ParseIntError {
4560 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4561 self.__description().fmt(f)
4565 #[stable(feature = "rust1", since = "1.0.0")]
4566 pub use num::dec2flt::ParseFloatError;
4568 // Conversion traits for primitive integer and float types
4569 // Conversions T -> T are covered by a blanket impl and therefore excluded
4570 // Some conversions from and to usize/isize are not implemented due to portability concerns
4571 macro_rules! impl_from {
4572 ($Small: ty, $Large: ty, #[$attr:meta], $doc: expr) => {
4575 impl From<$Small> for $Large {
4577 fn from(small: $Small) -> $Large {
4582 ($Small: ty, $Large: ty, #[$attr:meta]) => {
4586 concat!("Converts `",
4594 macro_rules! impl_from_bool {
4595 ($target: ty, #[$attr:meta]) => {
4596 impl_from!(bool, $target, #[$attr], concat!("Converts a `bool` to a `",
4597 stringify!($target), "`. The resulting value is `0` for `false` and `1` for `true`
4603 assert_eq!(", stringify!($target), "::from(true), 1);
4604 assert_eq!(", stringify!($target), "::from(false), 0);
4610 impl_from_bool! { u8, #[stable(feature = "from_bool", since = "1.28.0")] }
4611 impl_from_bool! { u16, #[stable(feature = "from_bool", since = "1.28.0")] }
4612 impl_from_bool! { u32, #[stable(feature = "from_bool", since = "1.28.0")] }
4613 impl_from_bool! { u64, #[stable(feature = "from_bool", since = "1.28.0")] }
4614 impl_from_bool! { u128, #[stable(feature = "from_bool", since = "1.28.0")] }
4615 impl_from_bool! { usize, #[stable(feature = "from_bool", since = "1.28.0")] }
4616 impl_from_bool! { i8, #[stable(feature = "from_bool", since = "1.28.0")] }
4617 impl_from_bool! { i16, #[stable(feature = "from_bool", since = "1.28.0")] }
4618 impl_from_bool! { i32, #[stable(feature = "from_bool", since = "1.28.0")] }
4619 impl_from_bool! { i64, #[stable(feature = "from_bool", since = "1.28.0")] }
4620 impl_from_bool! { i128, #[stable(feature = "from_bool", since = "1.28.0")] }
4621 impl_from_bool! { isize, #[stable(feature = "from_bool", since = "1.28.0")] }
4623 // Unsigned -> Unsigned
4624 impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4625 impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4626 impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4627 impl_from! { u8, u128, #[stable(feature = "i128", since = "1.26.0")] }
4628 impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4629 impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4630 impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4631 impl_from! { u16, u128, #[stable(feature = "i128", since = "1.26.0")] }
4632 impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4633 impl_from! { u32, u128, #[stable(feature = "i128", since = "1.26.0")] }
4634 impl_from! { u64, u128, #[stable(feature = "i128", since = "1.26.0")] }
4637 impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4638 impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4639 impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4640 impl_from! { i8, i128, #[stable(feature = "i128", since = "1.26.0")] }
4641 impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4642 impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4643 impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4644 impl_from! { i16, i128, #[stable(feature = "i128", since = "1.26.0")] }
4645 impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4646 impl_from! { i32, i128, #[stable(feature = "i128", since = "1.26.0")] }
4647 impl_from! { i64, i128, #[stable(feature = "i128", since = "1.26.0")] }
4649 // Unsigned -> Signed
4650 impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4651 impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4652 impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4653 impl_from! { u8, i128, #[stable(feature = "i128", since = "1.26.0")] }
4654 impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4655 impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4656 impl_from! { u16, i128, #[stable(feature = "i128", since = "1.26.0")] }
4657 impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4658 impl_from! { u32, i128, #[stable(feature = "i128", since = "1.26.0")] }
4659 impl_from! { u64, i128, #[stable(feature = "i128", since = "1.26.0")] }
4661 // The C99 standard defines bounds on INTPTR_MIN, INTPTR_MAX, and UINTPTR_MAX
4662 // which imply that pointer-sized integers must be at least 16 bits:
4663 // https://port70.net/~nsz/c/c99/n1256.html#7.18.2.4
4664 impl_from! { u16, usize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
4665 impl_from! { u8, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
4666 impl_from! { i16, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
4668 // RISC-V defines the possibility of a 128-bit address space (RV128).
4670 // CHERI proposes 256-bit “capabilities”. Unclear if this would be relevant to usize/isize.
4671 // https://www.cl.cam.ac.uk/research/security/ctsrd/pdfs/20171017a-cheri-poster.pdf
4672 // http://www.csl.sri.com/users/neumann/2012resolve-cheri.pdf
4675 // Note: integers can only be represented with full precision in a float if
4676 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
4677 // Lossy float conversions are not implemented at this time.
4680 impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4681 impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4682 impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4683 impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4684 impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4686 // Unsigned -> Float
4687 impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4688 impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4689 impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4690 impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4691 impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4694 impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4696 static ASCII_LOWERCASE_MAP: [u8; 256] = [
4697 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4698 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4699 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4700 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4701 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4702 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4703 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4704 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4707 b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4708 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4709 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4712 b'[', b'\\', b']', b'^', b'_',
4713 b'`', b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4714 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4715 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4716 b'x', b'y', b'z', b'{', b'|', b'}', b'~', 0x7f,
4717 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4718 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4719 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4720 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4721 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4722 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4723 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4724 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4725 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4726 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4727 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4728 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4729 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4730 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4731 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4732 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4735 static ASCII_UPPERCASE_MAP: [u8; 256] = [
4736 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4737 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4738 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4739 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4740 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4741 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4742 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4743 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4744 b'@', b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4745 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4746 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4747 b'X', b'Y', b'Z', b'[', b'\\', b']', b'^', b'_',
4750 b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4751 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4752 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4755 b'{', b'|', b'}', b'~', 0x7f,
4756 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4757 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4758 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4759 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4760 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4761 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4762 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4763 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4764 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4765 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4766 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4767 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4768 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4769 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4770 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4771 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4774 enum AsciiCharacterClass {
4776 Cw, // control whitespace
4780 Lx, // lowercase hex digit
4782 Ux, // uppercase hex digit
4785 use self::AsciiCharacterClass::*;
4787 static ASCII_CHARACTER_CLASS: [AsciiCharacterClass; 128] = [
4788 // _0 _1 _2 _3 _4 _5 _6 _7 _8 _9 _a _b _c _d _e _f
4789 C, C, C, C, C, C, C, C, C, Cw,Cw,C, Cw,Cw,C, C, // 0_
4790 C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, // 1_
4791 W, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, // 2_
4792 D, D, D, D, D, D, D, D, D, D, P, P, P, P, P, P, // 3_
4793 P, Ux,Ux,Ux,Ux,Ux,Ux,U, U, U, U, U, U, U, U, U, // 4_
4794 U, U, U, U, U, U, U, U, U, U, U, P, P, P, P, P, // 5_
4795 P, Lx,Lx,Lx,Lx,Lx,Lx,L, L, L, L, L, L, L, L, L, // 6_
4796 L, L, L, L, L, L, L, L, L, L, L, P, P, P, P, C, // 7_