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")]
18 #[allow(deprecated)] use nonzero::NonZero;
22 macro_rules! impl_nonzero_fmt {
23 ( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
26 impl fmt::$Trait for $Ty {
28 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
36 macro_rules! nonzero_integers {
37 ( #[$stability: meta] $( $Ty: ident($Int: ty); )+ ) => {
39 /// An integer that is known not to equal zero.
41 /// This may enable some memory layout optimization such as:
44 /// # #![feature(nonzero)]
45 /// use std::mem::size_of;
46 /// assert_eq!(size_of::<Option<std::num::NonZeroU32>>(), size_of::<u32>());
50 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
51 pub struct $Ty(NonZero<$Int>);
55 /// Create a non-zero without checking the value.
59 /// The value must not be zero.
62 pub const unsafe fn new_unchecked(n: $Int) -> Self {
66 /// Create a non-zero if the given value is not zero.
69 pub fn new(n: $Int) -> Option<Self> {
77 /// Returns the value as a primitive type.
80 pub fn get(self) -> $Int {
88 (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
95 #[unstable(feature = "nonzero", issue = "49137")]
96 NonZeroU8(u8); NonZeroI8(i8);
97 NonZeroU16(u16); NonZeroI16(i16);
98 NonZeroU32(u32); NonZeroI32(i32);
99 NonZeroU64(u64); NonZeroI64(i64);
100 NonZeroUsize(usize); NonZeroIsize(isize);
104 // Change this to `#[unstable(feature = "i128", issue = "35118")]`
105 // if other NonZero* integer types are stabilizied before 128-bit integers
106 #[unstable(feature = "nonzero", issue = "49137")]
107 NonZeroU128(u128); NonZeroI128(i128);
110 /// Provides intentionally-wrapped arithmetic on `T`.
112 /// Operations like `+` on `u32` values is intended to never overflow,
113 /// and in some debug configurations overflow is detected and results
114 /// in a panic. While most arithmetic falls into this category, some
115 /// code explicitly expects and relies upon modular arithmetic (e.g.,
118 /// Wrapping arithmetic can be achieved either through methods like
119 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
120 /// all standard arithmetic operations on the underlying value are
121 /// intended to have wrapping semantics.
126 /// use std::num::Wrapping;
128 /// let zero = Wrapping(0u32);
129 /// let one = Wrapping(1u32);
131 /// assert_eq!(std::u32::MAX, (zero - one).0);
133 #[stable(feature = "rust1", since = "1.0.0")]
134 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
135 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")]
138 #[stable(feature = "rust1", since = "1.0.0")]
139 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
140 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
145 #[stable(feature = "wrapping_display", since = "1.10.0")]
146 impl<T: fmt::Display> fmt::Display 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::Binary> fmt::Binary 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::Octal> fmt::Octal 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::LowerHex> fmt::LowerHex for Wrapping<T> {
168 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
173 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
174 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
175 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
182 // All these modules are technically private and only exposed for coretests:
188 macro_rules! doc_comment {
189 ($x:expr, $($tt:tt)*) => {
195 // `Int` + `SignedInt` implemented for signed integers
196 macro_rules! int_impl {
197 ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $Min:expr, $Max:expr, $Feature:expr,
198 $EndFeature:expr) => {
200 concat!("Returns the smallest value that can be represented by this integer type.
207 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), ", stringify!($Min), ");",
210 #[stable(feature = "rust1", since = "1.0.0")]
212 pub const fn min_value() -> Self {
213 !0 ^ ((!0 as $UnsignedT) >> 1) as Self
218 concat!("Returns the largest value that can be represented by this integer type.
225 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ", stringify!($Max), ");",
228 #[stable(feature = "rust1", since = "1.0.0")]
230 pub const fn max_value() -> Self {
236 concat!("Converts a string slice in a given base to an integer.
238 The string is expected to be an optional `+` or `-` sign followed by digits.
239 Leading and trailing whitespace represent an error. Digits are a subset of these characters,
240 depending on `radix`:
248 This function panics if `radix` is not in the range from 2 to 36.
255 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
258 #[stable(feature = "rust1", since = "1.0.0")]
259 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
260 from_str_radix(src, radix)
265 concat!("Returns the number of ones in the binary representation of `self`.
272 ", $Feature, "let n = 0b100_0000", stringify!($SelfT), ";
274 assert_eq!(n.count_ones(), 1);",
278 #[stable(feature = "rust1", since = "1.0.0")]
280 pub fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
284 concat!("Returns the number of zeros in the binary representation of `self`.
291 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 1);", $EndFeature, "
293 #[stable(feature = "rust1", since = "1.0.0")]
295 pub fn count_zeros(self) -> u32 {
301 concat!("Returns the number of leading zeros in the binary representation of `self`.
308 ", $Feature, "let n = -1", stringify!($SelfT), ";
310 assert_eq!(n.leading_zeros(), 0);",
313 #[stable(feature = "rust1", since = "1.0.0")]
315 pub fn leading_zeros(self) -> u32 {
316 (self as $UnsignedT).leading_zeros()
321 concat!("Returns the number of trailing zeros in the binary representation of `self`.
328 ", $Feature, "let n = -4", stringify!($SelfT), ";
330 assert_eq!(n.trailing_zeros(), 2);",
333 #[stable(feature = "rust1", since = "1.0.0")]
335 pub fn trailing_zeros(self) -> u32 {
336 (self as $UnsignedT).trailing_zeros()
340 /// Shifts the bits to the left by a specified amount, `n`,
341 /// wrapping the truncated bits to the end of the resulting integer.
343 /// Please note this isn't the same operation as `<<`!
347 /// Please note that this example is shared between integer types.
348 /// Which explains why `i64` is used here.
353 /// let n = 0x0123456789ABCDEFi64;
354 /// let m = -0x76543210FEDCBA99i64;
356 /// assert_eq!(n.rotate_left(32), m);
358 #[stable(feature = "rust1", since = "1.0.0")]
360 pub fn rotate_left(self, n: u32) -> Self {
361 (self as $UnsignedT).rotate_left(n) as Self
364 /// Shifts the bits to the right by a specified amount, `n`,
365 /// wrapping the truncated bits to the beginning of the resulting
368 /// Please note this isn't the same operation as `>>`!
372 /// Please note that this example is shared between integer types.
373 /// Which explains why `i64` is used here.
378 /// let n = 0x0123456789ABCDEFi64;
379 /// let m = -0xFEDCBA987654322i64;
381 /// assert_eq!(n.rotate_right(4), m);
383 #[stable(feature = "rust1", since = "1.0.0")]
385 pub fn rotate_right(self, n: u32) -> Self {
386 (self as $UnsignedT).rotate_right(n) as Self
389 /// Reverses the byte order of the integer.
393 /// Please note that this example is shared between integer types.
394 /// Which explains why `i16` is used here.
399 /// let n: i16 = 0b0000000_01010101;
400 /// assert_eq!(n, 85);
402 /// let m = n.swap_bytes();
404 /// assert_eq!(m, 0b01010101_00000000);
405 /// assert_eq!(m, 21760);
407 #[stable(feature = "rust1", since = "1.0.0")]
409 pub fn swap_bytes(self) -> Self {
410 (self as $UnsignedT).swap_bytes() as Self
413 /// Reverses the bit pattern of the integer.
417 /// Please note that this example is shared between integer types.
418 /// Which explains why `i16` is used here.
423 /// #![feature(reverse_bits)]
425 /// let n: i16 = 0b0000000_01010101;
426 /// assert_eq!(n, 85);
428 /// let m = n.reverse_bits();
430 /// assert_eq!(m as u16, 0b10101010_00000000);
431 /// assert_eq!(m, -22016);
433 #[unstable(feature = "reverse_bits", issue = "48763")]
436 pub fn reverse_bits(self) -> Self {
437 (self as $UnsignedT).reverse_bits() as Self
441 concat!("Converts an integer from big endian to the target's endianness.
443 On big endian this is a no-op. On little endian the bytes are swapped.
450 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
452 if cfg!(target_endian = \"big\") {
453 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
455 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
459 #[stable(feature = "rust1", since = "1.0.0")]
461 pub fn from_be(x: Self) -> Self {
462 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
467 concat!("Converts an integer from little endian to the target's endianness.
469 On little endian this is a no-op. On big endian the bytes are swapped.
476 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
478 if cfg!(target_endian = \"little\") {
479 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
481 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
485 #[stable(feature = "rust1", since = "1.0.0")]
487 pub fn from_le(x: Self) -> Self {
488 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
493 concat!("Converts `self` to big endian from the target's endianness.
495 On big endian this is a no-op. On little endian the bytes are swapped.
502 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
504 if cfg!(target_endian = \"big\") {
505 assert_eq!(n.to_be(), n)
507 assert_eq!(n.to_be(), n.swap_bytes())
511 #[stable(feature = "rust1", since = "1.0.0")]
513 pub fn to_be(self) -> Self { // or not to be?
514 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
519 concat!("Converts `self` to little endian from the target's endianness.
521 On little endian this is a no-op. On big endian the bytes are swapped.
528 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
530 if cfg!(target_endian = \"little\") {
531 assert_eq!(n.to_le(), n)
533 assert_eq!(n.to_le(), n.swap_bytes())
537 #[stable(feature = "rust1", since = "1.0.0")]
539 pub fn to_le(self) -> Self {
540 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
545 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
546 if overflow occurred.
553 ", $Feature, "assert_eq!((", stringify!($SelfT),
554 "::max_value() - 2).checked_add(1), Some(", stringify!($SelfT), "::max_value() - 1));
555 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);",
558 #[stable(feature = "rust1", since = "1.0.0")]
560 pub fn checked_add(self, rhs: Self) -> Option<Self> {
561 let (a, b) = self.overflowing_add(rhs);
562 if b {None} else {Some(a)}
567 concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
575 ", $Feature, "assert_eq!((", stringify!($SelfT),
576 "::min_value() + 2).checked_sub(1), Some(", stringify!($SelfT), "::min_value() + 1));
577 assert_eq!((", stringify!($SelfT), "::min_value() + 2).checked_sub(3), None);",
580 #[stable(feature = "rust1", since = "1.0.0")]
582 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
583 let (a, b) = self.overflowing_sub(rhs);
584 if b {None} else {Some(a)}
589 concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
597 ", $Feature, "assert_eq!(", stringify!($SelfT),
598 "::max_value().checked_mul(1), Some(", stringify!($SelfT), "::max_value()));
599 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);",
602 #[stable(feature = "rust1", since = "1.0.0")]
604 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
605 let (a, b) = self.overflowing_mul(rhs);
606 if b {None} else {Some(a)}
611 concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
612 or the division results in overflow.
619 ", $Feature, "assert_eq!((", stringify!($SelfT),
620 "::min_value() + 1).checked_div(-1), Some(", stringify!($Max), "));
621 assert_eq!(", stringify!($SelfT), "::min_value().checked_div(-1), None);
622 assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
625 #[stable(feature = "rust1", since = "1.0.0")]
627 pub fn checked_div(self, rhs: Self) -> Option<Self> {
628 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
631 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
637 concat!("Checked Euclidean division. Computes `self.div_euc(rhs)`, returning `None` if `rhs == 0`
638 or the division results in overflow.
645 ", $Feature, "assert_eq!((", stringify!($SelfT),
646 "::min_value() + 1).checked_div_euc(-1), Some(", stringify!($Max), "));
647 assert_eq!(", stringify!($SelfT), "::min_value().checked_div_euc(-1), None);
648 assert_eq!((1", stringify!($SelfT), ").checked_div_euc(0), None);",
651 #[unstable(feature = "euclidean_division", issue = "49048")]
653 pub fn checked_div_euc(self, rhs: Self) -> Option<Self> {
654 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
657 Some(self.div_euc(rhs))
663 concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
664 `rhs == 0` or the division results in overflow.
671 ", $Feature, "use std::", stringify!($SelfT), ";
673 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
674 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
675 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
678 #[stable(feature = "wrapping", since = "1.7.0")]
680 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
681 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
684 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
690 concat!("Checked Euclidean modulo. Computes `self.mod_euc(rhs)`, returning `None` if
691 `rhs == 0` or the division results in overflow.
698 ", $Feature, "use std::", stringify!($SelfT), ";
700 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(2), Some(1));
701 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(0), None);
702 assert_eq!(", stringify!($SelfT), "::MIN.checked_mod_euc(-1), None);",
705 #[unstable(feature = "euclidean_division", issue = "49048")]
707 pub fn checked_mod_euc(self, rhs: Self) -> Option<Self> {
708 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
711 Some(self.mod_euc(rhs))
717 concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
724 ", $Feature, "use std::", stringify!($SelfT), ";
726 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
727 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
730 #[stable(feature = "wrapping", since = "1.7.0")]
732 pub fn checked_neg(self) -> Option<Self> {
733 let (a, b) = self.overflowing_neg();
734 if b {None} else {Some(a)}
739 concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
740 than or equal to the number of bits in `self`.
747 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
748 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
751 #[stable(feature = "wrapping", since = "1.7.0")]
753 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
754 let (a, b) = self.overflowing_shl(rhs);
755 if b {None} else {Some(a)}
760 concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
761 larger than or equal to the number of bits in `self`.
768 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
769 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
772 #[stable(feature = "wrapping", since = "1.7.0")]
774 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
775 let (a, b) = self.overflowing_shr(rhs);
776 if b {None} else {Some(a)}
781 concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
789 ", $Feature, "use std::", stringify!($SelfT), ";
791 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
792 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
795 #[stable(feature = "no_panic_abs", since = "1.13.0")]
797 pub fn checked_abs(self) -> Option<Self> {
798 if self.is_negative() {
807 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
815 #![feature(no_panic_pow)]
816 ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
817 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);",
821 #[unstable(feature = "no_panic_pow", issue = "48320")]
823 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
825 let mut acc: Self = 1;
829 acc = acc.checked_mul(base)?;
832 base = base.checked_mul(base)?;
835 // Deal with the final bit of the exponent separately, since
836 // squaring the base afterwards is not necessary and may cause a
837 // needless overflow.
839 acc = acc.checked_mul(base)?;
847 concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
848 bounds instead of overflowing.
855 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
856 assert_eq!(", stringify!($SelfT), "::max_value().saturating_add(100), ", stringify!($SelfT),
860 #[stable(feature = "rust1", since = "1.0.0")]
862 pub fn saturating_add(self, rhs: Self) -> Self {
863 match self.checked_add(rhs) {
865 None if rhs >= 0 => Self::max_value(),
866 None => Self::min_value(),
872 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
873 numeric bounds instead of overflowing.
880 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
881 assert_eq!(", stringify!($SelfT), "::min_value().saturating_sub(100), ", stringify!($SelfT),
885 #[stable(feature = "rust1", since = "1.0.0")]
887 pub fn saturating_sub(self, rhs: Self) -> Self {
888 match self.checked_sub(rhs) {
890 None if rhs >= 0 => Self::min_value(),
891 None => Self::max_value(),
897 concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
898 numeric bounds instead of overflowing.
905 ", $Feature, "use std::", stringify!($SelfT), ";
907 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
908 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
909 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
912 #[stable(feature = "wrapping", since = "1.7.0")]
914 pub fn saturating_mul(self, rhs: Self) -> Self {
915 self.checked_mul(rhs).unwrap_or_else(|| {
916 if (self < 0 && rhs < 0) || (self > 0 && rhs > 0) {
926 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
927 saturating at the numeric bounds instead of overflowing.
934 #![feature(no_panic_pow)]
935 ", $Feature, "use std::", stringify!($SelfT), ";
937 assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
938 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
939 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
942 #[unstable(feature = "no_panic_pow", issue = "48320")]
944 pub fn saturating_pow(self, exp: u32) -> Self {
945 match self.checked_pow(exp) {
947 None if self < 0 && exp % 2 == 1 => Self::min_value(),
948 None => Self::max_value(),
954 concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
955 boundary of the type.
962 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
963 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_add(2), ", stringify!($SelfT),
964 "::min_value() + 1);",
967 #[stable(feature = "rust1", since = "1.0.0")]
969 pub fn wrapping_add(self, rhs: Self) -> Self {
971 intrinsics::overflowing_add(self, rhs)
977 concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
978 boundary of the type.
985 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
986 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::max_value()), ",
987 stringify!($SelfT), "::max_value());",
990 #[stable(feature = "rust1", since = "1.0.0")]
992 pub fn wrapping_sub(self, rhs: Self) -> Self {
994 intrinsics::overflowing_sub(self, rhs)
1000 concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1001 the boundary of the type.
1008 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
1009 assert_eq!(11i8.wrapping_mul(12), -124);",
1012 #[stable(feature = "rust1", since = "1.0.0")]
1014 pub fn wrapping_mul(self, rhs: Self) -> Self {
1016 intrinsics::overflowing_mul(self, rhs)
1022 concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1023 boundary of the type.
1025 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1026 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1027 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1031 This function will panic if `rhs` is 0.
1038 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
1039 assert_eq!((-128i8).wrapping_div(-1), -128);",
1042 #[stable(feature = "num_wrapping", since = "1.2.0")]
1044 pub fn wrapping_div(self, rhs: Self) -> Self {
1045 self.overflowing_div(rhs).0
1050 concat!("Wrapping Euclidean division. Computes `self.div_euc(rhs)`, wrapping around at the
1051 boundary of the type.
1053 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1054 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1055 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1059 This function will panic if `rhs` is 0.
1066 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euc(10), 10);
1067 assert_eq!((-128i8).wrapping_div_euc(-1), -128);",
1070 #[unstable(feature = "euclidean_division", issue = "49048")]
1072 pub fn wrapping_div_euc(self, rhs: Self) -> Self {
1073 self.overflowing_div_euc(rhs).0
1078 concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1079 boundary of the type.
1081 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1082 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1083 this function returns `0`.
1087 This function will panic if `rhs` is 0.
1094 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
1095 assert_eq!((-128i8).wrapping_rem(-1), 0);",
1098 #[stable(feature = "num_wrapping", since = "1.2.0")]
1100 pub fn wrapping_rem(self, rhs: Self) -> Self {
1101 self.overflowing_rem(rhs).0
1106 concat!("Wrapping Euclidean modulo. Computes `self.mod_euc(rhs)`, wrapping around at the
1107 boundary of the type.
1109 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1110 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1111 this function returns `0`.
1115 This function will panic if `rhs` is 0.
1122 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_mod_euc(10), 0);
1123 assert_eq!((-128i8).wrapping_mod_euc(-1), 0);",
1126 #[unstable(feature = "euclidean_division", issue = "49048")]
1128 pub fn wrapping_mod_euc(self, rhs: Self) -> Self {
1129 self.overflowing_mod_euc(rhs).0
1134 concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1137 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1138 is the negative minimal value for the type); this is a positive value that is too large to represent
1139 in the type. In such a case, this function returns `MIN` itself.
1146 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
1147 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_neg(), ", stringify!($SelfT),
1151 #[stable(feature = "num_wrapping", since = "1.2.0")]
1153 pub fn wrapping_neg(self) -> Self {
1154 self.overflowing_neg().0
1159 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1160 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1162 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1163 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1164 The primitive integer types all implement a `rotate_left` function, which may be what you want
1172 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
1173 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
1176 #[stable(feature = "num_wrapping", since = "1.2.0")]
1178 pub fn wrapping_shl(self, rhs: u32) -> Self {
1180 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1186 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1187 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1189 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1190 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1191 end. The primitive integer types all implement a `rotate_right` function, which may be what you want
1199 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
1200 assert_eq!((-128i16).wrapping_shr(64), -128);",
1203 #[stable(feature = "num_wrapping", since = "1.2.0")]
1205 pub fn wrapping_shr(self, rhs: u32) -> Self {
1207 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1213 concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1214 the boundary of the type.
1216 The only case where such wrapping can occur is when one takes the absolute value of the negative
1217 minimal value for the type this is a positive value that is too large to represent in the type. In
1218 such a case, this function returns `MIN` itself.
1225 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
1226 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
1227 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_abs(), ", stringify!($SelfT),
1229 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1232 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1234 pub fn wrapping_abs(self) -> Self {
1235 if self.is_negative() {
1244 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1245 wrapping around at the boundary of the type.
1252 #![feature(no_panic_pow)]
1253 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);
1254 assert_eq!(3i8.wrapping_pow(5), -13);
1255 assert_eq!(3i8.wrapping_pow(6), -39);",
1258 #[unstable(feature = "no_panic_pow", issue = "48320")]
1260 pub fn wrapping_pow(self, mut exp: u32) -> Self {
1261 let mut base = self;
1262 let mut acc: Self = 1;
1266 acc = acc.wrapping_mul(base);
1269 base = base.wrapping_mul(base);
1272 // Deal with the final bit of the exponent separately, since
1273 // squaring the base afterwards is not necessary and may cause a
1274 // needless overflow.
1276 acc = acc.wrapping_mul(base);
1284 concat!("Calculates `self` + `rhs`
1286 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1287 occur. If an overflow would have occurred then the wrapped value is returned.
1294 ", $Feature, "use std::", stringify!($SelfT), ";
1296 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1297 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
1298 "::MIN, true));", $EndFeature, "
1301 #[stable(feature = "wrapping", since = "1.7.0")]
1302 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1303 let (a, b) = unsafe {
1304 intrinsics::add_with_overflow(self as $ActualT,
1312 concat!("Calculates `self` - `rhs`
1314 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1315 would 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_sub(2), (3, false));
1325 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
1326 "::MAX, true));", $EndFeature, "
1329 #[stable(feature = "wrapping", since = "1.7.0")]
1330 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1331 let (a, b) = unsafe {
1332 intrinsics::sub_with_overflow(self as $ActualT,
1340 concat!("Calculates the multiplication of `self` and `rhs`.
1342 Returns a tuple of the multiplication 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, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1351 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1355 #[stable(feature = "wrapping", since = "1.7.0")]
1356 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1357 let (a, b) = unsafe {
1358 intrinsics::mul_with_overflow(self as $ActualT,
1366 concat!("Calculates the divisor when `self` is divided by `rhs`.
1368 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1369 occur. If an overflow would occur then self is returned.
1373 This function will panic if `rhs` is 0.
1380 ", $Feature, "use std::", stringify!($SelfT), ";
1382 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1383 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1388 #[stable(feature = "wrapping", since = "1.7.0")]
1389 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1390 if self == Self::min_value() && rhs == -1 {
1399 concat!("Calculates the quotient of Euclidean division `self.div_euc(rhs)`.
1401 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1402 occur. If an overflow would occur then self is returned.
1406 This function will panic if `rhs` is 0.
1413 ", $Feature, "use std::", stringify!($SelfT), ";
1415 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euc(2), (2, false));
1416 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euc(-1), (", stringify!($SelfT),
1421 #[unstable(feature = "euclidean_division", issue = "49048")]
1422 pub fn overflowing_div_euc(self, rhs: Self) -> (Self, bool) {
1423 if self == Self::min_value() && rhs == -1 {
1426 (self.div_euc(rhs), false)
1432 concat!("Calculates the remainder when `self` is divided by `rhs`.
1434 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1435 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1439 This function will panic if `rhs` is 0.
1446 ", $Feature, "use std::", stringify!($SelfT), ";
1448 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1449 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1453 #[stable(feature = "wrapping", since = "1.7.0")]
1454 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1455 if self == Self::min_value() && rhs == -1 {
1465 concat!("Calculates the modulo of Euclidean divsion `self.mod_euc(rhs)`.
1467 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1468 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1472 This function will panic if `rhs` is 0.
1479 ", $Feature, "use std::", stringify!($SelfT), ";
1481 assert_eq!(5", stringify!($SelfT), ".overflowing_mod_euc(2), (1, false));
1482 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_mod_euc(-1), (0, true));",
1485 #[unstable(feature = "euclidean_division", issue = "49048")]
1487 pub fn overflowing_mod_euc(self, rhs: Self) -> (Self, bool) {
1488 if self == Self::min_value() && rhs == -1 {
1491 (self.mod_euc(rhs), false)
1498 concat!("Negates self, overflowing if this is equal to the minimum value.
1500 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1501 happened. If `self` is the minimum value (e.g. `i32::MIN` for values of type `i32`), then the
1502 minimum value will be returned again and `true` will be returned for an overflow happening.
1509 ", $Feature, "use std::", stringify!($SelfT), ";
1511 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1512 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1513 "::MIN, true));", $EndFeature, "
1516 #[stable(feature = "wrapping", since = "1.7.0")]
1517 pub fn overflowing_neg(self) -> (Self, bool) {
1518 if self == Self::min_value() {
1519 (Self::min_value(), true)
1527 concat!("Shifts self left by `rhs` bits.
1529 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1530 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1531 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1538 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1539 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1543 #[stable(feature = "wrapping", since = "1.7.0")]
1544 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1545 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1550 concat!("Shifts self right by `rhs` bits.
1552 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1553 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1554 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1561 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1562 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1566 #[stable(feature = "wrapping", since = "1.7.0")]
1567 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1568 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1573 concat!("Computes the absolute value of `self`.
1575 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1576 happened. If self is the minimum value (e.g. ", stringify!($SelfT), "::MIN for values of type
1577 ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1578 for an overflow happening.
1585 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1586 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1587 assert_eq!((", stringify!($SelfT), "::min_value()).overflowing_abs(), (", stringify!($SelfT),
1588 "::min_value(), true));",
1591 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1593 pub fn overflowing_abs(self) -> (Self, bool) {
1594 if self.is_negative() {
1595 self.overflowing_neg()
1603 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1605 Returns a tuple of the exponentiation along with a bool indicating
1606 whether an overflow happened.
1613 #![feature(no_panic_pow)]
1614 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));
1615 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
1618 #[unstable(feature = "no_panic_pow", issue = "48320")]
1620 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1621 let mut base = self;
1622 let mut acc: Self = 1;
1623 let mut overflown = false;
1624 // Scratch space for storing results of overflowing_mul.
1629 r = acc.overflowing_mul(base);
1634 r = base.overflowing_mul(base);
1639 // Deal with the final bit of the exponent separately, since
1640 // squaring the base afterwards is not necessary and may cause a
1641 // needless overflow.
1643 r = acc.overflowing_mul(base);
1653 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1660 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
1662 assert_eq!(x.pow(5), 32);",
1665 #[stable(feature = "rust1", since = "1.0.0")]
1667 #[rustc_inherit_overflow_checks]
1668 pub fn pow(self, mut exp: u32) -> Self {
1669 let mut base = self;
1680 // Deal with the final bit of the exponent separately, since
1681 // squaring the base afterwards is not necessary and may cause a
1682 // needless overflow.
1692 concat!("Calculates the quotient of Euclidean division of `self` by `rhs`.
1694 This computes the integer n such that `self = n * rhs + self.mod_euc(rhs)`.
1695 In other words, the result is `self / rhs` rounded to the integer n
1696 such that `self >= n * rhs`.
1700 This function will panic if `rhs` is 0.
1707 ", $Feature, "let a: ", stringify!($SelfT), " = 7; // or any other integer type
1710 assert_eq!(a.div_euc(b), 1); // 7 >= 4 * 1
1711 assert_eq!(a.div_euc(-b), -1); // 7 >= -4 * -1
1712 assert_eq!((-a).div_euc(b), -2); // -7 >= 4 * -2
1713 assert_eq!((-a).div_euc(-b), 2); // -7 >= -4 * 2",
1716 #[unstable(feature = "euclidean_division", issue = "49048")]
1718 #[rustc_inherit_overflow_checks]
1719 pub fn div_euc(self, rhs: Self) -> Self {
1722 return if rhs > 0 { q - 1 } else { q + 1 }
1730 concat!("Calculates the modulo `self mod rhs` by Euclidean division.
1732 In particular, the result `n` satisfies `0 <= n < rhs.abs()`.
1736 This function will panic if `rhs` is 0.
1743 ", $Feature, "let a: ", stringify!($SelfT), " = 7; // or any other integer type
1746 assert_eq!(a.mod_euc(b), 3);
1747 assert_eq!((-a).mod_euc(b), 1);
1748 assert_eq!(a.mod_euc(-b), 3);
1749 assert_eq!((-a).mod_euc(-b), 1);",
1752 #[unstable(feature = "euclidean_division", issue = "49048")]
1754 #[rustc_inherit_overflow_checks]
1755 pub fn mod_euc(self, rhs: Self) -> Self {
1766 concat!("Computes the absolute value of `self`.
1770 The absolute value of `", stringify!($SelfT), "::min_value()` cannot be represented as an
1771 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
1772 code in debug mode will trigger a panic on this case and optimized code will return `",
1773 stringify!($SelfT), "::min_value()` without a panic.
1780 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
1781 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
1784 #[stable(feature = "rust1", since = "1.0.0")]
1786 #[rustc_inherit_overflow_checks]
1787 pub fn abs(self) -> Self {
1788 if self.is_negative() {
1789 // Note that the #[inline] above means that the overflow
1790 // semantics of this negation depend on the crate we're being
1800 concat!("Returns a number representing sign of `self`.
1802 - `0` if the number is zero
1803 - `1` if the number is positive
1804 - `-1` if the number is negative
1811 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
1812 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
1813 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
1816 #[stable(feature = "rust1", since = "1.0.0")]
1818 pub fn signum(self) -> Self {
1828 concat!("Returns `true` if `self` is positive and `false` if the number is zero or
1836 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
1837 assert!(!(-10", stringify!($SelfT), ").is_positive());",
1840 #[stable(feature = "rust1", since = "1.0.0")]
1842 pub fn is_positive(self) -> bool { self > 0 }
1846 concat!("Returns `true` if `self` is negative and `false` if the number is zero or
1854 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
1855 assert!(!10", stringify!($SelfT), ".is_negative());",
1858 #[stable(feature = "rust1", since = "1.0.0")]
1860 pub fn is_negative(self) -> bool { self < 0 }
1867 int_impl! { i8, i8, u8, 8, -128, 127, "", "" }
1872 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "" }
1877 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "" }
1882 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "" }
1887 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
1888 170141183460469231731687303715884105727, "#![feature(i128_type)]
1895 #[cfg(target_pointer_width = "16")]
1898 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "" }
1901 #[cfg(target_pointer_width = "32")]
1904 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "" }
1907 #[cfg(target_pointer_width = "64")]
1910 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "" }
1913 // `Int` + `UnsignedInt` implemented for unsigned integers
1914 macro_rules! uint_impl {
1915 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr) => {
1917 concat!("Returns the smallest value that can be represented by this integer type.
1924 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), 0);", $EndFeature, "
1926 #[stable(feature = "rust1", since = "1.0.0")]
1928 pub const fn min_value() -> Self { 0 }
1932 concat!("Returns the largest value that can be represented by this integer type.
1939 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ",
1940 stringify!($MaxV), ");", $EndFeature, "
1942 #[stable(feature = "rust1", since = "1.0.0")]
1944 pub const fn max_value() -> Self { !0 }
1948 concat!("Converts a string slice in a given base to an integer.
1950 The string is expected to be an optional `+` sign
1952 Leading and trailing whitespace represent an error.
1953 Digits are a subset of these characters, depending on `radix`:
1961 This function panics if `radix` is not in the range from 2 to 36.
1968 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
1971 #[stable(feature = "rust1", since = "1.0.0")]
1972 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
1973 from_str_radix(src, radix)
1978 concat!("Returns the number of ones in the binary representation of `self`.
1985 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
1987 assert_eq!(n.count_ones(), 3);", $EndFeature, "
1989 #[stable(feature = "rust1", since = "1.0.0")]
1991 pub fn count_ones(self) -> u32 {
1992 unsafe { intrinsics::ctpop(self as $ActualT) as u32 }
1997 concat!("Returns the number of zeros in the binary representation of `self`.
2004 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 0);", $EndFeature, "
2006 #[stable(feature = "rust1", since = "1.0.0")]
2008 pub fn count_zeros(self) -> u32 {
2009 (!self).count_ones()
2014 concat!("Returns the number of leading zeros in the binary representation of `self`.
2021 ", $Feature, "let n = ", stringify!($SelfT), "::max_value() >> 2;
2023 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
2025 #[stable(feature = "rust1", since = "1.0.0")]
2027 pub fn leading_zeros(self) -> u32 {
2028 unsafe { intrinsics::ctlz(self as $ActualT) as u32 }
2033 concat!("Returns the number of trailing zeros in the binary representation
2041 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
2043 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
2045 #[stable(feature = "rust1", since = "1.0.0")]
2047 pub fn trailing_zeros(self) -> u32 {
2048 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
2049 // emits two conditional moves on x86_64. By promoting the value to
2050 // u16 and setting bit 8, we get better code without any conditional
2052 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
2053 // pending, remove this workaround once LLVM generates better code
2057 intrinsics::cttz(self as u16 | 0x100) as u32
2059 intrinsics::cttz(self) as u32
2065 /// Shifts the bits to the left by a specified amount, `n`,
2066 /// wrapping the truncated bits to the end of the resulting integer.
2068 /// Please note this isn't the same operation as `<<`!
2074 /// Please note that this example is shared between integer types.
2075 /// Which explains why `u64` is used here.
2078 /// let n = 0x0123456789ABCDEFu64;
2079 /// let m = 0x3456789ABCDEF012u64;
2081 /// assert_eq!(n.rotate_left(12), m);
2083 #[stable(feature = "rust1", since = "1.0.0")]
2085 pub fn rotate_left(self, n: u32) -> Self {
2086 // Protect against undefined behaviour for over-long bit shifts
2088 (self << n) | (self >> (($BITS - n) % $BITS))
2091 /// Shifts the bits to the right by a specified amount, `n`,
2092 /// wrapping the truncated bits to the beginning of the resulting
2095 /// Please note this isn't the same operation as `>>`!
2101 /// Please note that this example is shared between integer types.
2102 /// Which explains why `u64` is used here.
2105 /// let n = 0x0123456789ABCDEFu64;
2106 /// let m = 0xDEF0123456789ABCu64;
2108 /// assert_eq!(n.rotate_right(12), m);
2110 #[stable(feature = "rust1", since = "1.0.0")]
2112 pub fn rotate_right(self, n: u32) -> Self {
2113 // Protect against undefined behaviour for over-long bit shifts
2115 (self >> n) | (self << (($BITS - n) % $BITS))
2118 /// Reverses the byte order of the integer.
2124 /// Please note that this example is shared between integer types.
2125 /// Which explains why `u16` is used here.
2128 /// let n: u16 = 0b0000000_01010101;
2129 /// assert_eq!(n, 85);
2131 /// let m = n.swap_bytes();
2133 /// assert_eq!(m, 0b01010101_00000000);
2134 /// assert_eq!(m, 21760);
2136 #[stable(feature = "rust1", since = "1.0.0")]
2138 pub fn swap_bytes(self) -> Self {
2139 unsafe { intrinsics::bswap(self as $ActualT) as Self }
2142 /// Reverses the bit pattern of the integer.
2148 /// Please note that this example is shared between integer types.
2149 /// Which explains why `u16` is used here.
2152 /// #![feature(reverse_bits)]
2154 /// let n: u16 = 0b0000000_01010101;
2155 /// assert_eq!(n, 85);
2157 /// let m = n.reverse_bits();
2159 /// assert_eq!(m, 0b10101010_00000000);
2160 /// assert_eq!(m, 43520);
2162 #[unstable(feature = "reverse_bits", issue = "48763")]
2165 pub fn reverse_bits(self) -> Self {
2166 unsafe { intrinsics::bitreverse(self as $ActualT) as Self }
2170 concat!("Converts an integer from big endian to the target's endianness.
2172 On big endian this is a no-op. On little endian the bytes are
2180 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2182 if cfg!(target_endian = \"big\") {
2183 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
2185 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
2188 #[stable(feature = "rust1", since = "1.0.0")]
2190 pub fn from_be(x: Self) -> Self {
2191 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
2196 concat!("Converts an integer from little endian to the target's endianness.
2198 On little endian this is a no-op. On big endian the bytes are
2206 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2208 if cfg!(target_endian = \"little\") {
2209 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
2211 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
2214 #[stable(feature = "rust1", since = "1.0.0")]
2216 pub fn from_le(x: Self) -> Self {
2217 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
2222 concat!("Converts `self` to big endian from the target's endianness.
2224 On big endian this is a no-op. On little endian the bytes are
2232 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2234 if cfg!(target_endian = \"big\") {
2235 assert_eq!(n.to_be(), n)
2237 assert_eq!(n.to_be(), n.swap_bytes())
2240 #[stable(feature = "rust1", since = "1.0.0")]
2242 pub fn to_be(self) -> Self { // or not to be?
2243 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
2248 concat!("Converts `self` to little endian from the target's endianness.
2250 On little endian this is a no-op. On big endian the bytes are
2258 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2260 if cfg!(target_endian = \"little\") {
2261 assert_eq!(n.to_le(), n)
2263 assert_eq!(n.to_le(), n.swap_bytes())
2266 #[stable(feature = "rust1", since = "1.0.0")]
2268 pub fn to_le(self) -> Self {
2269 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
2274 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2275 if overflow occurred.
2282 ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), ",
2283 "Some(", stringify!($SelfT), "::max_value() - 1));
2284 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3),None);", $EndFeature, "
2286 #[stable(feature = "rust1", since = "1.0.0")]
2288 pub fn checked_add(self, rhs: Self) -> Option<Self> {
2289 let (a, b) = self.overflowing_add(rhs);
2290 if b {None} else {Some(a)}
2295 concat!("Checked integer subtraction. Computes `self - rhs`, returning
2296 `None` if overflow occurred.
2303 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
2304 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
2306 #[stable(feature = "rust1", since = "1.0.0")]
2308 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
2309 let (a, b) = self.overflowing_sub(rhs);
2310 if b {None} else {Some(a)}
2315 concat!("Checked integer multiplication. Computes `self * rhs`, returning
2316 `None` if overflow occurred.
2323 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
2324 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, "
2326 #[stable(feature = "rust1", since = "1.0.0")]
2328 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
2329 let (a, b) = self.overflowing_mul(rhs);
2330 if b {None} else {Some(a)}
2335 concat!("Checked integer division. Computes `self / rhs`, returning `None`
2343 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2344 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2346 #[stable(feature = "rust1", since = "1.0.0")]
2348 pub fn checked_div(self, rhs: Self) -> Option<Self> {
2351 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
2357 concat!("Checked Euclidean division. Computes `self.div_euc(rhs)`, returning `None`
2365 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2366 assert_eq!(1", stringify!($SelfT), ".checked_div_euc(0), None);
2368 #[unstable(feature = "euclidean_division", issue = "49048")]
2370 pub fn checked_div_euc(self, rhs: Self) -> Option<Self> {
2374 Some(self.div_euc(rhs))
2381 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
2389 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
2390 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
2392 #[stable(feature = "wrapping", since = "1.7.0")]
2394 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
2398 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
2404 concat!("Checked Euclidean modulo. Computes `self.mod_euc(rhs)`, returning `None`
2412 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(2), Some(1));
2413 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(0), None);",
2416 #[unstable(feature = "euclidean_division", issue = "49048")]
2418 pub fn checked_mod_euc(self, rhs: Self) -> Option<Self> {
2422 Some(self.mod_euc(rhs))
2428 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
2431 Note that negating any positive integer will overflow.
2438 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
2439 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
2441 #[stable(feature = "wrapping", since = "1.7.0")]
2443 pub fn checked_neg(self) -> Option<Self> {
2444 let (a, b) = self.overflowing_neg();
2445 if b {None} else {Some(a)}
2450 concat!("Checked shift left. Computes `self << rhs`, returning `None`
2451 if `rhs` is larger than or equal to the number of bits in `self`.
2458 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
2459 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
2461 #[stable(feature = "wrapping", since = "1.7.0")]
2463 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
2464 let (a, b) = self.overflowing_shl(rhs);
2465 if b {None} else {Some(a)}
2470 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
2471 if `rhs` is larger than or equal to the number of bits in `self`.
2478 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
2479 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
2481 #[stable(feature = "wrapping", since = "1.7.0")]
2483 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
2484 let (a, b) = self.overflowing_shr(rhs);
2485 if b {None} else {Some(a)}
2490 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
2498 #![feature(no_panic_pow)]
2499 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
2500 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, "
2502 #[unstable(feature = "no_panic_pow", issue = "48320")]
2504 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
2505 let mut base = self;
2506 let mut acc: Self = 1;
2510 acc = acc.checked_mul(base)?;
2513 base = base.checked_mul(base)?;
2516 // Deal with the final bit of the exponent separately, since
2517 // squaring the base afterwards is not necessary and may cause a
2518 // needless overflow.
2520 acc = acc.checked_mul(base)?;
2528 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
2529 the numeric bounds instead of overflowing.
2536 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
2537 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
2539 #[stable(feature = "rust1", since = "1.0.0")]
2541 pub fn saturating_add(self, rhs: Self) -> Self {
2542 match self.checked_add(rhs) {
2544 None => Self::max_value(),
2550 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
2551 at the numeric bounds instead of overflowing.
2558 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
2559 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
2561 #[stable(feature = "rust1", since = "1.0.0")]
2563 pub fn saturating_sub(self, rhs: Self) -> Self {
2564 match self.checked_sub(rhs) {
2566 None => Self::min_value(),
2572 concat!("Saturating integer multiplication. Computes `self * rhs`,
2573 saturating at the numeric bounds instead of overflowing.
2580 ", $Feature, "use std::", stringify!($SelfT), ";
2582 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
2583 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
2584 "::MAX);", $EndFeature, "
2586 #[stable(feature = "wrapping", since = "1.7.0")]
2588 pub fn saturating_mul(self, rhs: Self) -> Self {
2589 self.checked_mul(rhs).unwrap_or(Self::max_value())
2594 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
2595 saturating at the numeric bounds instead of overflowing.
2602 #![feature(no_panic_pow)]
2603 ", $Feature, "use std::", stringify!($SelfT), ";
2605 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
2606 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
2609 #[unstable(feature = "no_panic_pow", issue = "48320")]
2611 pub fn saturating_pow(self, exp: u32) -> Self {
2612 match self.checked_pow(exp) {
2614 None => Self::max_value(),
2620 concat!("Wrapping (modular) addition. Computes `self + rhs`,
2621 wrapping around at the boundary of the type.
2628 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
2629 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
2632 #[stable(feature = "rust1", since = "1.0.0")]
2634 pub fn wrapping_add(self, rhs: Self) -> Self {
2636 intrinsics::overflowing_add(self, rhs)
2642 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
2643 wrapping around at the boundary of the type.
2650 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
2651 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
2654 #[stable(feature = "rust1", since = "1.0.0")]
2656 pub fn wrapping_sub(self, rhs: Self) -> Self {
2658 intrinsics::overflowing_sub(self, rhs)
2663 /// Wrapping (modular) multiplication. Computes `self *
2664 /// rhs`, wrapping around at the boundary of the type.
2670 /// Please note that this example is shared between integer types.
2671 /// Which explains why `u8` is used here.
2674 /// assert_eq!(10u8.wrapping_mul(12), 120);
2675 /// assert_eq!(25u8.wrapping_mul(12), 44);
2677 #[stable(feature = "rust1", since = "1.0.0")]
2679 pub fn wrapping_mul(self, rhs: Self) -> Self {
2681 intrinsics::overflowing_mul(self, rhs)
2686 concat!("Wrapping (modular) division. Computes `self / rhs`.
2687 Wrapped division on unsigned types is just normal division.
2688 There's no way wrapping could ever happen.
2689 This function exists, so that all operations
2690 are accounted for in the wrapping operations.
2697 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
2699 #[stable(feature = "num_wrapping", since = "1.2.0")]
2701 pub fn wrapping_div(self, rhs: Self) -> Self {
2707 concat!("Wrapping Euclidean division. Computes `self.div_euc(rhs)`.
2708 Wrapped division on unsigned types is just normal division.
2709 There's no way wrapping could ever happen.
2710 This function exists, so that all operations
2711 are accounted for in the wrapping operations.
2718 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div_euc(10), 10);", $EndFeature, "
2720 #[unstable(feature = "euclidean_division", issue = "49048")]
2722 pub fn wrapping_div_euc(self, rhs: Self) -> Self {
2728 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
2729 Wrapped remainder calculation on unsigned types is
2730 just the regular remainder calculation.
2731 There's no way wrapping could ever happen.
2732 This function exists, so that all operations
2733 are accounted for in the wrapping operations.
2740 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
2742 #[stable(feature = "num_wrapping", since = "1.2.0")]
2744 pub fn wrapping_rem(self, rhs: Self) -> Self {
2750 concat!("Wrapping Euclidean modulo. Computes `self.mod_euc(rhs)`.
2751 Wrapped modulo calculation on unsigned types is
2752 just the regular remainder calculation.
2753 There's no way wrapping could ever happen.
2754 This function exists, so that all operations
2755 are accounted for in the wrapping operations.
2762 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_mod_euc(10), 0);", $EndFeature, "
2764 #[unstable(feature = "euclidean_division", issue = "49048")]
2766 pub fn wrapping_mod_euc(self, rhs: Self) -> Self {
2771 /// Wrapping (modular) negation. Computes `-self`,
2772 /// wrapping around at the boundary of the type.
2774 /// Since unsigned types do not have negative equivalents
2775 /// all applications of this function will wrap (except for `-0`).
2776 /// For values smaller than the corresponding signed type's maximum
2777 /// the result is the same as casting the corresponding signed value.
2778 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
2779 /// `MAX` is the corresponding signed type's maximum.
2785 /// Please note that this example is shared between integer types.
2786 /// Which explains why `i8` is used here.
2789 /// assert_eq!(100i8.wrapping_neg(), -100);
2790 /// assert_eq!((-128i8).wrapping_neg(), -128);
2792 #[stable(feature = "num_wrapping", since = "1.2.0")]
2794 pub fn wrapping_neg(self) -> Self {
2795 self.overflowing_neg().0
2799 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
2800 where `mask` removes any high-order bits of `rhs` that
2801 would cause the shift to exceed the bitwidth of the type.
2803 Note that this is *not* the same as a rotate-left; the
2804 RHS of a wrapping shift-left is restricted to the range
2805 of the type, rather than the bits shifted out of the LHS
2806 being returned to the other end. The primitive integer
2807 types all implement a `rotate_left` function, which may
2808 be what you want instead.
2815 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
2816 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
2818 #[stable(feature = "num_wrapping", since = "1.2.0")]
2820 pub fn wrapping_shl(self, rhs: u32) -> Self {
2822 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
2828 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
2829 where `mask` removes any high-order bits of `rhs` that
2830 would cause the shift to exceed the bitwidth of the type.
2832 Note that this is *not* the same as a rotate-right; the
2833 RHS of a wrapping shift-right is restricted to the range
2834 of the type, rather than the bits shifted out of the LHS
2835 being returned to the other end. The primitive integer
2836 types all implement a `rotate_right` function, which may
2837 be what you want instead.
2844 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
2845 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
2847 #[stable(feature = "num_wrapping", since = "1.2.0")]
2849 pub fn wrapping_shr(self, rhs: u32) -> Self {
2851 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
2857 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
2858 wrapping around at the boundary of the type.
2865 #![feature(no_panic_pow)]
2866 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
2867 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
2869 #[unstable(feature = "no_panic_pow", issue = "48320")]
2871 pub fn wrapping_pow(self, mut exp: u32) -> Self {
2872 let mut base = self;
2873 let mut acc: Self = 1;
2877 acc = acc.wrapping_mul(base);
2880 base = base.wrapping_mul(base);
2883 // Deal with the final bit of the exponent separately, since
2884 // squaring the base afterwards is not necessary and may cause a
2885 // needless overflow.
2887 acc = acc.wrapping_mul(base);
2895 concat!("Calculates `self` + `rhs`
2897 Returns a tuple of the addition along with a boolean indicating
2898 whether an arithmetic overflow would occur. If an overflow would
2899 have occurred then the wrapped value is returned.
2906 ", $Feature, "use std::", stringify!($SelfT), ";
2908 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
2909 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
2912 #[stable(feature = "wrapping", since = "1.7.0")]
2913 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
2914 let (a, b) = unsafe {
2915 intrinsics::add_with_overflow(self as $ActualT,
2923 concat!("Calculates `self` - `rhs`
2925 Returns a tuple of the subtraction along with a boolean indicating
2926 whether an arithmetic overflow would occur. If an overflow would
2927 have occurred then the wrapped value is returned.
2934 ", $Feature, "use std::", stringify!($SelfT), ";
2936 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
2937 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
2941 #[stable(feature = "wrapping", since = "1.7.0")]
2942 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
2943 let (a, b) = unsafe {
2944 intrinsics::sub_with_overflow(self as $ActualT,
2951 /// Calculates the multiplication of `self` and `rhs`.
2953 /// Returns a tuple of the multiplication along with a boolean
2954 /// indicating whether an arithmetic overflow would occur. If an
2955 /// overflow would have occurred then the wrapped value is returned.
2961 /// Please note that this example is shared between integer types.
2962 /// Which explains why `u32` is used here.
2965 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
2966 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
2969 #[stable(feature = "wrapping", since = "1.7.0")]
2970 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
2971 let (a, b) = unsafe {
2972 intrinsics::mul_with_overflow(self as $ActualT,
2979 concat!("Calculates the divisor when `self` is divided by `rhs`.
2981 Returns a tuple of the divisor along with a boolean indicating
2982 whether an arithmetic overflow would occur. Note that for unsigned
2983 integers overflow never occurs, so the second value is always
2988 This function will panic if `rhs` is 0.
2995 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
2998 #[stable(feature = "wrapping", since = "1.7.0")]
2999 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3005 concat!("Calculates the quotient of Euclidean division `self.div_euc(rhs)`.
3007 Returns a tuple of the divisor along with a boolean indicating
3008 whether an arithmetic overflow would occur. Note that for unsigned
3009 integers overflow never occurs, so the second value is always
3014 This function will panic if `rhs` is 0.
3021 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div_euc(2), (2, false));", $EndFeature, "
3024 #[unstable(feature = "euclidean_division", issue = "49048")]
3025 pub fn overflowing_div_euc(self, rhs: Self) -> (Self, bool) {
3031 concat!("Calculates the remainder when `self` is divided by `rhs`.
3033 Returns a tuple of the remainder after dividing along with a boolean
3034 indicating whether an arithmetic overflow would occur. Note that for
3035 unsigned integers overflow never occurs, so the second value is
3040 This function will panic if `rhs` is 0.
3047 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3050 #[stable(feature = "wrapping", since = "1.7.0")]
3051 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3057 concat!("Calculates the modulo of Euclidean division of `self.mod_euc(rhs)`.
3059 Returns a tuple of the modulo after dividing along with a boolean
3060 indicating whether an arithmetic overflow would occur. Note that for
3061 unsigned integers overflow never occurs, so the second value is
3066 This function will panic if `rhs` is 0.
3073 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mod_euc(2), (1, false));", $EndFeature, "
3076 #[unstable(feature = "euclidean_division", issue = "49048")]
3077 pub fn overflowing_mod_euc(self, rhs: Self) -> (Self, bool) {
3083 concat!("Negates self in an overflowing fashion.
3085 Returns `!self + 1` using wrapping operations to return the value
3086 that represents the negation of this unsigned value. Note that for
3087 positive unsigned values overflow always occurs, but negating 0 does
3095 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3096 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3097 ", true));", $EndFeature, "
3100 #[stable(feature = "wrapping", since = "1.7.0")]
3101 pub fn overflowing_neg(self) -> (Self, bool) {
3102 ((!self).wrapping_add(1), self != 0)
3107 concat!("Shifts self left by `rhs` bits.
3109 Returns a tuple of the shifted version of self along with a boolean
3110 indicating whether the shift value was larger than or equal to the
3111 number of bits. If the shift value is too large, then value is
3112 masked (N-1) where N is the number of bits, and this value is then
3113 used to perform the shift.
3120 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3121 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3124 #[stable(feature = "wrapping", since = "1.7.0")]
3125 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3126 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3131 concat!("Shifts self right by `rhs` bits.
3133 Returns a tuple of the shifted version of self along with a boolean
3134 indicating whether the shift value was larger than or equal to the
3135 number of bits. If the shift value is too large, then value is
3136 masked (N-1) where N is the number of bits, and this value is then
3137 used to perform the shift.
3144 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
3145 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
3148 #[stable(feature = "wrapping", since = "1.7.0")]
3149 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3150 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
3155 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3157 Returns a tuple of the exponentiation along with a bool indicating
3158 whether an overflow happened.
3165 #![feature(no_panic_pow)]
3166 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
3167 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
3169 #[unstable(feature = "no_panic_pow", issue = "48320")]
3171 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3172 let mut base = self;
3173 let mut acc: Self = 1;
3174 let mut overflown = false;
3175 // Scratch space for storing results of overflowing_mul.
3180 r = acc.overflowing_mul(base);
3185 r = base.overflowing_mul(base);
3190 // Deal with the final bit of the exponent separately, since
3191 // squaring the base afterwards is not necessary and may cause a
3192 // needless overflow.
3194 r = acc.overflowing_mul(base);
3204 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3211 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
3213 #[stable(feature = "rust1", since = "1.0.0")]
3215 #[rustc_inherit_overflow_checks]
3216 pub fn pow(self, mut exp: u32) -> Self {
3217 let mut base = self;
3228 // Deal with the final bit of the exponent separately, since
3229 // squaring the base afterwards is not necessary and may cause a
3230 // needless overflow.
3240 concat!("Performs Euclidean division.
3242 For unsigned types, this is just the same as `self / rhs`.
3249 ", $Feature, "assert_eq(7", stringify!($SelfT), ".div_euc(4), 1); // or any other integer type",
3252 #[unstable(feature = "euclidean_division", issue = "49048")]
3254 #[rustc_inherit_overflow_checks]
3255 pub fn div_euc(self, rhs: Self) -> Self {
3262 concat!("Calculates the Euclidean modulo `self mod rhs`.
3264 For unsigned types, this is just the same as `self % rhs`.
3271 ", $Feature, "assert_eq(7", stringify!($SelfT), ".mod_euc(4), 3); // or any other integer type",
3274 #[unstable(feature = "euclidean_division", issue = "49048")]
3276 #[rustc_inherit_overflow_checks]
3277 pub fn mod_euc(self, rhs: Self) -> Self {
3283 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
3290 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
3291 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
3293 #[stable(feature = "rust1", since = "1.0.0")]
3295 pub fn is_power_of_two(self) -> bool {
3296 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
3300 // Returns one less than next power of two.
3301 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
3303 // 8u8.one_less_than_next_power_of_two() == 7
3304 // 6u8.one_less_than_next_power_of_two() == 7
3306 // This method cannot overflow, as in the `next_power_of_two`
3307 // overflow cases it instead ends up returning the maximum value
3308 // of the type, and can return 0 for 0.
3310 fn one_less_than_next_power_of_two(self) -> Self {
3311 if self <= 1 { return 0; }
3313 // Because `p > 0`, it cannot consist entirely of leading zeros.
3314 // That means the shift is always in-bounds, and some processors
3315 // (such as intel pre-haswell) have more efficient ctlz
3316 // intrinsics when the argument is non-zero.
3318 let z = unsafe { intrinsics::ctlz_nonzero(p) };
3319 <$SelfT>::max_value() >> z
3323 concat!("Returns the smallest power of two greater than or equal to `self`.
3325 When return value overflows (i.e. `self > (1 << (N-1))` for type
3326 `uN`), it panics in debug mode and return value is wrapped to 0 in
3327 release mode (the only situation in which method can return 0).
3334 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
3335 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
3337 #[stable(feature = "rust1", since = "1.0.0")]
3339 pub fn next_power_of_two(self) -> Self {
3340 // Call the trait to get overflow checks
3341 ops::Add::add(self.one_less_than_next_power_of_two(), 1)
3346 concat!("Returns the smallest power of two greater than or equal to `n`. If
3347 the next power of two is greater than the type's maximum value,
3348 `None` is returned, otherwise the power of two is wrapped in `Some`.
3355 ", $Feature, "assert_eq!(2", stringify!($SelfT),
3356 ".checked_next_power_of_two(), Some(2));
3357 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
3358 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
3361 #[stable(feature = "rust1", since = "1.0.0")]
3362 pub fn checked_next_power_of_two(self) -> Option<Self> {
3363 self.one_less_than_next_power_of_two().checked_add(1)
3371 uint_impl! { u8, u8, 8, 255, "", "" }
3374 /// Checks if the value is within the ASCII range.
3379 /// let ascii = 97u8;
3380 /// let non_ascii = 150u8;
3382 /// assert!(ascii.is_ascii());
3383 /// assert!(!non_ascii.is_ascii());
3385 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3387 pub fn is_ascii(&self) -> bool {
3391 /// Makes a copy of the value in its ASCII upper case equivalent.
3393 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3394 /// but non-ASCII letters are unchanged.
3396 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
3401 /// let lowercase_a = 97u8;
3403 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
3406 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
3407 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3409 pub fn to_ascii_uppercase(&self) -> u8 {
3410 ASCII_UPPERCASE_MAP[*self as usize]
3413 /// Makes a copy of the value in its ASCII lower case equivalent.
3415 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3416 /// but non-ASCII letters are unchanged.
3418 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
3423 /// let uppercase_a = 65u8;
3425 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
3428 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
3429 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3431 pub fn to_ascii_lowercase(&self) -> u8 {
3432 ASCII_LOWERCASE_MAP[*self as usize]
3435 /// Checks that two values are an ASCII case-insensitive match.
3437 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
3442 /// let lowercase_a = 97u8;
3443 /// let uppercase_a = 65u8;
3445 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
3447 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3449 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
3450 self.to_ascii_lowercase() == other.to_ascii_lowercase()
3453 /// Converts this value to its ASCII upper case equivalent in-place.
3455 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3456 /// but non-ASCII letters are unchanged.
3458 /// To return a new uppercased value without modifying the existing one, use
3459 /// [`to_ascii_uppercase`].
3464 /// let mut byte = b'a';
3466 /// byte.make_ascii_uppercase();
3468 /// assert_eq!(b'A', byte);
3471 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
3472 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3474 pub fn make_ascii_uppercase(&mut self) {
3475 *self = self.to_ascii_uppercase();
3478 /// Converts this value to its ASCII lower case equivalent in-place.
3480 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3481 /// but non-ASCII letters are unchanged.
3483 /// To return a new lowercased value without modifying the existing one, use
3484 /// [`to_ascii_lowercase`].
3489 /// let mut byte = b'A';
3491 /// byte.make_ascii_lowercase();
3493 /// assert_eq!(b'a', byte);
3496 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
3497 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3499 pub fn make_ascii_lowercase(&mut self) {
3500 *self = self.to_ascii_lowercase();
3503 /// Checks if the value is an ASCII alphabetic character:
3505 /// - U+0041 'A' ... U+005A 'Z', or
3506 /// - U+0061 'a' ... U+007A 'z'.
3511 /// #![feature(ascii_ctype)]
3513 /// let uppercase_a = b'A';
3514 /// let uppercase_g = b'G';
3517 /// let zero = b'0';
3518 /// let percent = b'%';
3519 /// let space = b' ';
3521 /// let esc = 0x1b_u8;
3523 /// assert!(uppercase_a.is_ascii_alphabetic());
3524 /// assert!(uppercase_g.is_ascii_alphabetic());
3525 /// assert!(a.is_ascii_alphabetic());
3526 /// assert!(g.is_ascii_alphabetic());
3527 /// assert!(!zero.is_ascii_alphabetic());
3528 /// assert!(!percent.is_ascii_alphabetic());
3529 /// assert!(!space.is_ascii_alphabetic());
3530 /// assert!(!lf.is_ascii_alphabetic());
3531 /// assert!(!esc.is_ascii_alphabetic());
3533 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3535 pub fn is_ascii_alphabetic(&self) -> bool {
3536 if *self >= 0x80 { return false; }
3537 match ASCII_CHARACTER_CLASS[*self as usize] {
3538 L | Lx | U | Ux => true,
3543 /// Checks if the value is an ASCII uppercase character:
3544 /// U+0041 'A' ... U+005A 'Z'.
3549 /// #![feature(ascii_ctype)]
3551 /// let uppercase_a = b'A';
3552 /// let uppercase_g = b'G';
3555 /// let zero = b'0';
3556 /// let percent = b'%';
3557 /// let space = b' ';
3559 /// let esc = 0x1b_u8;
3561 /// assert!(uppercase_a.is_ascii_uppercase());
3562 /// assert!(uppercase_g.is_ascii_uppercase());
3563 /// assert!(!a.is_ascii_uppercase());
3564 /// assert!(!g.is_ascii_uppercase());
3565 /// assert!(!zero.is_ascii_uppercase());
3566 /// assert!(!percent.is_ascii_uppercase());
3567 /// assert!(!space.is_ascii_uppercase());
3568 /// assert!(!lf.is_ascii_uppercase());
3569 /// assert!(!esc.is_ascii_uppercase());
3571 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3573 pub fn is_ascii_uppercase(&self) -> bool {
3574 if *self >= 0x80 { return false }
3575 match ASCII_CHARACTER_CLASS[*self as usize] {
3581 /// Checks if the value is an ASCII lowercase character:
3582 /// U+0061 'a' ... U+007A 'z'.
3587 /// #![feature(ascii_ctype)]
3589 /// let uppercase_a = b'A';
3590 /// let uppercase_g = b'G';
3593 /// let zero = b'0';
3594 /// let percent = b'%';
3595 /// let space = b' ';
3597 /// let esc = 0x1b_u8;
3599 /// assert!(!uppercase_a.is_ascii_lowercase());
3600 /// assert!(!uppercase_g.is_ascii_lowercase());
3601 /// assert!(a.is_ascii_lowercase());
3602 /// assert!(g.is_ascii_lowercase());
3603 /// assert!(!zero.is_ascii_lowercase());
3604 /// assert!(!percent.is_ascii_lowercase());
3605 /// assert!(!space.is_ascii_lowercase());
3606 /// assert!(!lf.is_ascii_lowercase());
3607 /// assert!(!esc.is_ascii_lowercase());
3609 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3611 pub fn is_ascii_lowercase(&self) -> bool {
3612 if *self >= 0x80 { return false }
3613 match ASCII_CHARACTER_CLASS[*self as usize] {
3619 /// Checks if the value is an ASCII alphanumeric character:
3621 /// - U+0041 'A' ... U+005A 'Z', or
3622 /// - U+0061 'a' ... U+007A 'z', or
3623 /// - U+0030 '0' ... U+0039 '9'.
3628 /// #![feature(ascii_ctype)]
3630 /// let uppercase_a = b'A';
3631 /// let uppercase_g = b'G';
3634 /// let zero = b'0';
3635 /// let percent = b'%';
3636 /// let space = b' ';
3638 /// let esc = 0x1b_u8;
3640 /// assert!(uppercase_a.is_ascii_alphanumeric());
3641 /// assert!(uppercase_g.is_ascii_alphanumeric());
3642 /// assert!(a.is_ascii_alphanumeric());
3643 /// assert!(g.is_ascii_alphanumeric());
3644 /// assert!(zero.is_ascii_alphanumeric());
3645 /// assert!(!percent.is_ascii_alphanumeric());
3646 /// assert!(!space.is_ascii_alphanumeric());
3647 /// assert!(!lf.is_ascii_alphanumeric());
3648 /// assert!(!esc.is_ascii_alphanumeric());
3650 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3652 pub fn is_ascii_alphanumeric(&self) -> bool {
3653 if *self >= 0x80 { return false }
3654 match ASCII_CHARACTER_CLASS[*self as usize] {
3655 D | L | Lx | U | Ux => true,
3660 /// Checks if the value is an ASCII decimal digit:
3661 /// U+0030 '0' ... U+0039 '9'.
3666 /// #![feature(ascii_ctype)]
3668 /// let uppercase_a = b'A';
3669 /// let uppercase_g = b'G';
3672 /// let zero = b'0';
3673 /// let percent = b'%';
3674 /// let space = b' ';
3676 /// let esc = 0x1b_u8;
3678 /// assert!(!uppercase_a.is_ascii_digit());
3679 /// assert!(!uppercase_g.is_ascii_digit());
3680 /// assert!(!a.is_ascii_digit());
3681 /// assert!(!g.is_ascii_digit());
3682 /// assert!(zero.is_ascii_digit());
3683 /// assert!(!percent.is_ascii_digit());
3684 /// assert!(!space.is_ascii_digit());
3685 /// assert!(!lf.is_ascii_digit());
3686 /// assert!(!esc.is_ascii_digit());
3688 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3690 pub fn is_ascii_digit(&self) -> bool {
3691 if *self >= 0x80 { return false }
3692 match ASCII_CHARACTER_CLASS[*self as usize] {
3698 /// Checks if the value is an ASCII hexadecimal digit:
3700 /// - U+0030 '0' ... U+0039 '9', or
3701 /// - U+0041 'A' ... U+0046 'F', or
3702 /// - U+0061 'a' ... U+0066 'f'.
3707 /// #![feature(ascii_ctype)]
3709 /// let uppercase_a = b'A';
3710 /// let uppercase_g = b'G';
3713 /// let zero = b'0';
3714 /// let percent = b'%';
3715 /// let space = b' ';
3717 /// let esc = 0x1b_u8;
3719 /// assert!(uppercase_a.is_ascii_hexdigit());
3720 /// assert!(!uppercase_g.is_ascii_hexdigit());
3721 /// assert!(a.is_ascii_hexdigit());
3722 /// assert!(!g.is_ascii_hexdigit());
3723 /// assert!(zero.is_ascii_hexdigit());
3724 /// assert!(!percent.is_ascii_hexdigit());
3725 /// assert!(!space.is_ascii_hexdigit());
3726 /// assert!(!lf.is_ascii_hexdigit());
3727 /// assert!(!esc.is_ascii_hexdigit());
3729 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3731 pub fn is_ascii_hexdigit(&self) -> bool {
3732 if *self >= 0x80 { return false }
3733 match ASCII_CHARACTER_CLASS[*self as usize] {
3734 D | Lx | Ux => true,
3739 /// Checks if the value is an ASCII punctuation character:
3741 /// - U+0021 ... U+002F `! " # $ % & ' ( ) * + , - . /`, or
3742 /// - U+003A ... U+0040 `: ; < = > ? @`, or
3743 /// - U+005B ... U+0060 ``[ \ ] ^ _ ` ``, or
3744 /// - U+007B ... U+007E `{ | } ~`
3749 /// #![feature(ascii_ctype)]
3751 /// let uppercase_a = b'A';
3752 /// let uppercase_g = b'G';
3755 /// let zero = b'0';
3756 /// let percent = b'%';
3757 /// let space = b' ';
3759 /// let esc = 0x1b_u8;
3761 /// assert!(!uppercase_a.is_ascii_punctuation());
3762 /// assert!(!uppercase_g.is_ascii_punctuation());
3763 /// assert!(!a.is_ascii_punctuation());
3764 /// assert!(!g.is_ascii_punctuation());
3765 /// assert!(!zero.is_ascii_punctuation());
3766 /// assert!(percent.is_ascii_punctuation());
3767 /// assert!(!space.is_ascii_punctuation());
3768 /// assert!(!lf.is_ascii_punctuation());
3769 /// assert!(!esc.is_ascii_punctuation());
3771 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3773 pub fn is_ascii_punctuation(&self) -> bool {
3774 if *self >= 0x80 { return false }
3775 match ASCII_CHARACTER_CLASS[*self as usize] {
3781 /// Checks if the value is an ASCII graphic character:
3782 /// U+0021 '!' ... U+007E '~'.
3787 /// #![feature(ascii_ctype)]
3789 /// let uppercase_a = b'A';
3790 /// let uppercase_g = b'G';
3793 /// let zero = b'0';
3794 /// let percent = b'%';
3795 /// let space = b' ';
3797 /// let esc = 0x1b_u8;
3799 /// assert!(uppercase_a.is_ascii_graphic());
3800 /// assert!(uppercase_g.is_ascii_graphic());
3801 /// assert!(a.is_ascii_graphic());
3802 /// assert!(g.is_ascii_graphic());
3803 /// assert!(zero.is_ascii_graphic());
3804 /// assert!(percent.is_ascii_graphic());
3805 /// assert!(!space.is_ascii_graphic());
3806 /// assert!(!lf.is_ascii_graphic());
3807 /// assert!(!esc.is_ascii_graphic());
3809 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3811 pub fn is_ascii_graphic(&self) -> bool {
3812 if *self >= 0x80 { return false; }
3813 match ASCII_CHARACTER_CLASS[*self as usize] {
3814 Ux | U | Lx | L | D | P => true,
3819 /// Checks if the value is an ASCII whitespace character:
3820 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
3821 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
3823 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
3824 /// whitespace][infra-aw]. There are several other definitions in
3825 /// wide use. For instance, [the POSIX locale][pct] includes
3826 /// U+000B VERTICAL TAB as well as all the above characters,
3827 /// but—from the very same specification—[the default rule for
3828 /// "field splitting" in the Bourne shell][bfs] considers *only*
3829 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
3831 /// If you are writing a program that will process an existing
3832 /// file format, check what that format's definition of whitespace is
3833 /// before using this function.
3835 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
3836 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
3837 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
3842 /// #![feature(ascii_ctype)]
3844 /// let uppercase_a = b'A';
3845 /// let uppercase_g = b'G';
3848 /// let zero = b'0';
3849 /// let percent = b'%';
3850 /// let space = b' ';
3852 /// let esc = 0x1b_u8;
3854 /// assert!(!uppercase_a.is_ascii_whitespace());
3855 /// assert!(!uppercase_g.is_ascii_whitespace());
3856 /// assert!(!a.is_ascii_whitespace());
3857 /// assert!(!g.is_ascii_whitespace());
3858 /// assert!(!zero.is_ascii_whitespace());
3859 /// assert!(!percent.is_ascii_whitespace());
3860 /// assert!(space.is_ascii_whitespace());
3861 /// assert!(lf.is_ascii_whitespace());
3862 /// assert!(!esc.is_ascii_whitespace());
3864 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3866 pub fn is_ascii_whitespace(&self) -> bool {
3867 if *self >= 0x80 { return false; }
3868 match ASCII_CHARACTER_CLASS[*self as usize] {
3874 /// Checks if the value is an ASCII control character:
3875 /// U+0000 NUL ... U+001F UNIT SEPARATOR, or U+007F DELETE.
3876 /// Note that most ASCII whitespace characters are control
3877 /// characters, but SPACE is not.
3882 /// #![feature(ascii_ctype)]
3884 /// let uppercase_a = b'A';
3885 /// let uppercase_g = b'G';
3888 /// let zero = b'0';
3889 /// let percent = b'%';
3890 /// let space = b' ';
3892 /// let esc = 0x1b_u8;
3894 /// assert!(!uppercase_a.is_ascii_control());
3895 /// assert!(!uppercase_g.is_ascii_control());
3896 /// assert!(!a.is_ascii_control());
3897 /// assert!(!g.is_ascii_control());
3898 /// assert!(!zero.is_ascii_control());
3899 /// assert!(!percent.is_ascii_control());
3900 /// assert!(!space.is_ascii_control());
3901 /// assert!(lf.is_ascii_control());
3902 /// assert!(esc.is_ascii_control());
3904 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3906 pub fn is_ascii_control(&self) -> bool {
3907 if *self >= 0x80 { return false; }
3908 match ASCII_CHARACTER_CLASS[*self as usize] {
3917 uint_impl! { u16, u16, 16, 65535, "", "" }
3922 uint_impl! { u32, u32, 32, 4294967295, "", "" }
3927 uint_impl! { u64, u64, 64, 18446744073709551615, "", "" }
3932 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "#![feature(i128_type)]
3940 #[cfg(target_pointer_width = "16")]
3943 uint_impl! { usize, u16, 16, 65536, "", "" }
3945 #[cfg(target_pointer_width = "32")]
3948 uint_impl! { usize, u32, 32, 4294967295, "", "" }
3951 #[cfg(target_pointer_width = "64")]
3954 uint_impl! { usize, u64, 64, 18446744073709551615, "", "" }
3957 /// A classification of floating point numbers.
3959 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
3960 /// their documentation for more.
3962 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
3963 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
3968 /// use std::num::FpCategory;
3971 /// let num = 12.4_f32;
3972 /// let inf = f32::INFINITY;
3973 /// let zero = 0f32;
3974 /// let sub: f32 = 1.1754942e-38;
3975 /// let nan = f32::NAN;
3977 /// assert_eq!(num.classify(), FpCategory::Normal);
3978 /// assert_eq!(inf.classify(), FpCategory::Infinite);
3979 /// assert_eq!(zero.classify(), FpCategory::Zero);
3980 /// assert_eq!(nan.classify(), FpCategory::Nan);
3981 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
3983 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
3984 #[stable(feature = "rust1", since = "1.0.0")]
3985 pub enum FpCategory {
3986 /// "Not a Number", often obtained by dividing by zero.
3987 #[stable(feature = "rust1", since = "1.0.0")]
3990 /// Positive or negative infinity.
3991 #[stable(feature = "rust1", since = "1.0.0")]
3994 /// Positive or negative zero.
3995 #[stable(feature = "rust1", since = "1.0.0")]
3998 /// De-normalized floating point representation (less precise than `Normal`).
3999 #[stable(feature = "rust1", since = "1.0.0")]
4002 /// A regular floating point number.
4003 #[stable(feature = "rust1", since = "1.0.0")]
4007 /// A built-in floating point number.
4009 #[unstable(feature = "core_float",
4010 reason = "stable interface is via `impl f{32,64}` in later crates",
4012 pub trait Float: Sized {
4013 /// Type used by `to_bits` and `from_bits`.
4014 #[stable(feature = "core_float_bits", since = "1.25.0")]
4017 /// Returns `true` if this value is NaN and false otherwise.
4018 #[stable(feature = "core", since = "1.6.0")]
4019 fn is_nan(self) -> bool;
4020 /// Returns `true` if this value is positive infinity or negative infinity and
4021 /// false otherwise.
4022 #[stable(feature = "core", since = "1.6.0")]
4023 fn is_infinite(self) -> bool;
4024 /// Returns `true` if this number is neither infinite nor NaN.
4025 #[stable(feature = "core", since = "1.6.0")]
4026 fn is_finite(self) -> bool;
4027 /// Returns `true` if this number is neither zero, infinite, denormal, or NaN.
4028 #[stable(feature = "core", since = "1.6.0")]
4029 fn is_normal(self) -> bool;
4030 /// Returns the category that this number falls into.
4031 #[stable(feature = "core", since = "1.6.0")]
4032 fn classify(self) -> FpCategory;
4034 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
4035 /// number is `Float::nan()`.
4036 #[stable(feature = "core", since = "1.6.0")]
4037 fn abs(self) -> Self;
4038 /// Returns a number that represents the sign of `self`.
4040 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
4041 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
4042 /// - `Float::nan()` if the number is `Float::nan()`
4043 #[stable(feature = "core", since = "1.6.0")]
4044 fn signum(self) -> Self;
4046 /// Returns `true` if `self` is positive, including `+0.0` and
4047 /// `Float::infinity()`.
4048 #[stable(feature = "core", since = "1.6.0")]
4049 fn is_sign_positive(self) -> bool;
4050 /// Returns `true` if `self` is negative, including `-0.0` and
4051 /// `Float::neg_infinity()`.
4052 #[stable(feature = "core", since = "1.6.0")]
4053 fn is_sign_negative(self) -> bool;
4055 /// Take the reciprocal (inverse) of a number, `1/x`.
4056 #[stable(feature = "core", since = "1.6.0")]
4057 fn recip(self) -> Self;
4059 /// Raise a number to an integer power.
4061 /// Using this function is generally faster than using `powf`
4062 #[stable(feature = "core", since = "1.6.0")]
4063 fn powi(self, n: i32) -> Self;
4065 /// Convert radians to degrees.
4066 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
4067 fn to_degrees(self) -> Self;
4068 /// Convert degrees to radians.
4069 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
4070 fn to_radians(self) -> Self;
4072 /// Returns the maximum of the two numbers.
4073 #[stable(feature = "core_float_min_max", since="1.20.0")]
4074 fn max(self, other: Self) -> Self;
4075 /// Returns the minimum of the two numbers.
4076 #[stable(feature = "core_float_min_max", since="1.20.0")]
4077 fn min(self, other: Self) -> Self;
4079 /// Raw transmutation to integer.
4080 #[stable(feature = "core_float_bits", since="1.25.0")]
4081 fn to_bits(self) -> Self::Bits;
4082 /// Raw transmutation from integer.
4083 #[stable(feature = "core_float_bits", since="1.25.0")]
4084 fn from_bits(v: Self::Bits) -> Self;
4087 macro_rules! from_str_radix_int_impl {
4089 #[stable(feature = "rust1", since = "1.0.0")]
4090 impl FromStr for $t {
4091 type Err = ParseIntError;
4092 fn from_str(src: &str) -> Result<Self, ParseIntError> {
4093 from_str_radix(src, 10)
4098 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
4100 /// The error type returned when a checked integral type conversion fails.
4101 #[unstable(feature = "try_from", issue = "33417")]
4102 #[derive(Debug, Copy, Clone)]
4103 pub struct TryFromIntError(());
4105 impl TryFromIntError {
4106 #[unstable(feature = "int_error_internals",
4107 reason = "available through Error trait and this method should \
4108 not be exposed publicly",
4111 pub fn __description(&self) -> &str {
4112 "out of range integral type conversion attempted"
4116 #[unstable(feature = "try_from", issue = "33417")]
4117 impl fmt::Display for TryFromIntError {
4118 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4119 self.__description().fmt(fmt)
4123 #[unstable(feature = "try_from", issue = "33417")]
4124 impl From<!> for TryFromIntError {
4125 fn from(never: !) -> TryFromIntError {
4130 // no possible bounds violation
4131 macro_rules! try_from_unbounded {
4132 ($source:ty, $($target:ty),*) => {$(
4133 #[unstable(feature = "try_from", issue = "33417")]
4134 impl TryFrom<$source> for $target {
4138 fn try_from(value: $source) -> Result<Self, Self::Error> {
4139 Ok(value as $target)
4145 // only negative bounds
4146 macro_rules! try_from_lower_bounded {
4147 ($source:ty, $($target:ty),*) => {$(
4148 #[unstable(feature = "try_from", issue = "33417")]
4149 impl TryFrom<$source> for $target {
4150 type Error = TryFromIntError;
4153 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4157 Err(TryFromIntError(()))
4164 // unsigned to signed (only positive bound)
4165 macro_rules! try_from_upper_bounded {
4166 ($source:ty, $($target:ty),*) => {$(
4167 #[unstable(feature = "try_from", issue = "33417")]
4168 impl TryFrom<$source> for $target {
4169 type Error = TryFromIntError;
4172 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4173 if u > (<$target>::max_value() as $source) {
4174 Err(TryFromIntError(()))
4184 macro_rules! try_from_both_bounded {
4185 ($source:ty, $($target:ty),*) => {$(
4186 #[unstable(feature = "try_from", issue = "33417")]
4187 impl TryFrom<$source> for $target {
4188 type Error = TryFromIntError;
4191 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4192 let min = <$target>::min_value() as $source;
4193 let max = <$target>::max_value() as $source;
4194 if u < min || u > max {
4195 Err(TryFromIntError(()))
4205 ($mac:ident, $source:ty, $($target:ty),*) => {$(
4206 $mac!($target, $source);
4210 /// intra-sign conversions
4211 try_from_upper_bounded!(u16, u8);
4212 try_from_upper_bounded!(u32, u16, u8);
4213 try_from_upper_bounded!(u64, u32, u16, u8);
4214 try_from_upper_bounded!(u128, u64, u32, u16, u8);
4216 try_from_both_bounded!(i16, i8);
4217 try_from_both_bounded!(i32, i16, i8);
4218 try_from_both_bounded!(i64, i32, i16, i8);
4219 try_from_both_bounded!(i128, i64, i32, i16, i8);
4221 // unsigned-to-signed
4222 try_from_upper_bounded!(u8, i8);
4223 try_from_upper_bounded!(u16, i8, i16);
4224 try_from_upper_bounded!(u32, i8, i16, i32);
4225 try_from_upper_bounded!(u64, i8, i16, i32, i64);
4226 try_from_upper_bounded!(u128, i8, i16, i32, i64, i128);
4228 // signed-to-unsigned
4229 try_from_lower_bounded!(i8, u8, u16, u32, u64, u128);
4230 try_from_lower_bounded!(i16, u16, u32, u64, u128);
4231 try_from_lower_bounded!(i32, u32, u64, u128);
4232 try_from_lower_bounded!(i64, u64, u128);
4233 try_from_lower_bounded!(i128, u128);
4234 try_from_both_bounded!(i16, u8);
4235 try_from_both_bounded!(i32, u16, u8);
4236 try_from_both_bounded!(i64, u32, u16, u8);
4237 try_from_both_bounded!(i128, u64, u32, u16, u8);
4240 try_from_upper_bounded!(usize, isize);
4241 try_from_lower_bounded!(isize, usize);
4243 #[cfg(target_pointer_width = "16")]
4244 mod ptr_try_from_impls {
4245 use super::TryFromIntError;
4246 use convert::TryFrom;
4248 try_from_upper_bounded!(usize, u8);
4249 try_from_unbounded!(usize, u16, u32, u64, u128);
4250 try_from_upper_bounded!(usize, i8, i16);
4251 try_from_unbounded!(usize, i32, i64, i128);
4253 try_from_both_bounded!(isize, u8);
4254 try_from_lower_bounded!(isize, u16, u32, u64, u128);
4255 try_from_both_bounded!(isize, i8);
4256 try_from_unbounded!(isize, i16, i32, i64, i128);
4258 rev!(try_from_unbounded, usize, u16);
4259 rev!(try_from_upper_bounded, usize, u32, u64, u128);
4260 rev!(try_from_lower_bounded, usize, i8, i16);
4261 rev!(try_from_both_bounded, usize, i32, i64, i128);
4263 rev!(try_from_unbounded, isize, u8);
4264 rev!(try_from_upper_bounded, isize, u16, u32, u64, u128);
4265 rev!(try_from_unbounded, isize, i16);
4266 rev!(try_from_both_bounded, isize, i32, i64, i128);
4269 #[cfg(target_pointer_width = "32")]
4270 mod ptr_try_from_impls {
4271 use super::TryFromIntError;
4272 use convert::TryFrom;
4274 try_from_upper_bounded!(usize, u8, u16);
4275 try_from_unbounded!(usize, u32, u64, u128);
4276 try_from_upper_bounded!(usize, i8, i16, i32);
4277 try_from_unbounded!(usize, i64, i128);
4279 try_from_both_bounded!(isize, u8, u16);
4280 try_from_lower_bounded!(isize, u32, u64, u128);
4281 try_from_both_bounded!(isize, i8, i16);
4282 try_from_unbounded!(isize, i32, i64, i128);
4284 rev!(try_from_unbounded, usize, u16, u32);
4285 rev!(try_from_upper_bounded, usize, u64, u128);
4286 rev!(try_from_lower_bounded, usize, i8, i16, i32);
4287 rev!(try_from_both_bounded, usize, i64, i128);
4289 rev!(try_from_unbounded, isize, u8, u16);
4290 rev!(try_from_upper_bounded, isize, u32, u64, u128);
4291 rev!(try_from_unbounded, isize, i16, i32);
4292 rev!(try_from_both_bounded, isize, i64, i128);
4295 #[cfg(target_pointer_width = "64")]
4296 mod ptr_try_from_impls {
4297 use super::TryFromIntError;
4298 use convert::TryFrom;
4300 try_from_upper_bounded!(usize, u8, u16, u32);
4301 try_from_unbounded!(usize, u64, u128);
4302 try_from_upper_bounded!(usize, i8, i16, i32, i64);
4303 try_from_unbounded!(usize, i128);
4305 try_from_both_bounded!(isize, u8, u16, u32);
4306 try_from_lower_bounded!(isize, u64, u128);
4307 try_from_both_bounded!(isize, i8, i16, i32);
4308 try_from_unbounded!(isize, i64, i128);
4310 rev!(try_from_unbounded, usize, u16, u32, u64);
4311 rev!(try_from_upper_bounded, usize, u128);
4312 rev!(try_from_lower_bounded, usize, i8, i16, i32, i64);
4313 rev!(try_from_both_bounded, usize, i128);
4315 rev!(try_from_unbounded, isize, u8, u16, u32);
4316 rev!(try_from_upper_bounded, isize, u64, u128);
4317 rev!(try_from_unbounded, isize, i16, i32, i64);
4318 rev!(try_from_both_bounded, isize, i128);
4322 trait FromStrRadixHelper: PartialOrd + Copy {
4323 fn min_value() -> Self;
4324 fn max_value() -> Self;
4325 fn from_u32(u: u32) -> Self;
4326 fn checked_mul(&self, other: u32) -> Option<Self>;
4327 fn checked_sub(&self, other: u32) -> Option<Self>;
4328 fn checked_add(&self, other: u32) -> Option<Self>;
4332 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
4334 fn min_value() -> Self { Self::min_value() }
4336 fn max_value() -> Self { Self::max_value() }
4338 fn from_u32(u: u32) -> Self { u as Self }
4340 fn checked_mul(&self, other: u32) -> Option<Self> {
4341 Self::checked_mul(*self, other as Self)
4344 fn checked_sub(&self, other: u32) -> Option<Self> {
4345 Self::checked_sub(*self, other as Self)
4348 fn checked_add(&self, other: u32) -> Option<Self> {
4349 Self::checked_add(*self, other as Self)
4353 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
4355 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
4356 use self::IntErrorKind::*;
4357 use self::ParseIntError as PIE;
4359 assert!(radix >= 2 && radix <= 36,
4360 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
4364 return Err(PIE { kind: Empty });
4367 let is_signed_ty = T::from_u32(0) > T::min_value();
4369 // all valid digits are ascii, so we will just iterate over the utf8 bytes
4370 // and cast them to chars. .to_digit() will safely return None for anything
4371 // other than a valid ascii digit for the given radix, including the first-byte
4372 // of multi-byte sequences
4373 let src = src.as_bytes();
4375 let (is_positive, digits) = match src[0] {
4376 b'+' => (true, &src[1..]),
4377 b'-' if is_signed_ty => (false, &src[1..]),
4381 if digits.is_empty() {
4382 return Err(PIE { kind: Empty });
4385 let mut result = T::from_u32(0);
4387 // The number is positive
4389 let x = match (c as char).to_digit(radix) {
4391 None => return Err(PIE { kind: InvalidDigit }),
4393 result = match result.checked_mul(radix) {
4394 Some(result) => result,
4395 None => return Err(PIE { kind: Overflow }),
4397 result = match result.checked_add(x) {
4398 Some(result) => result,
4399 None => return Err(PIE { kind: Overflow }),
4403 // The number is negative
4405 let x = match (c as char).to_digit(radix) {
4407 None => return Err(PIE { kind: InvalidDigit }),
4409 result = match result.checked_mul(radix) {
4410 Some(result) => result,
4411 None => return Err(PIE { kind: Underflow }),
4413 result = match result.checked_sub(x) {
4414 Some(result) => result,
4415 None => return Err(PIE { kind: Underflow }),
4422 /// An error which can be returned when parsing an integer.
4424 /// This error is used as the error type for the `from_str_radix()` functions
4425 /// on the primitive integer types, such as [`i8::from_str_radix`].
4427 /// # Potential causes
4429 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
4430 /// in the string e.g. when it is obtained from the standard input.
4431 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
4433 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
4434 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
4435 #[derive(Debug, Clone, PartialEq, Eq)]
4436 #[stable(feature = "rust1", since = "1.0.0")]
4437 pub struct ParseIntError {
4441 #[derive(Debug, Clone, PartialEq, Eq)]
4449 impl ParseIntError {
4450 #[unstable(feature = "int_error_internals",
4451 reason = "available through Error trait and this method should \
4452 not be exposed publicly",
4455 pub fn __description(&self) -> &str {
4457 IntErrorKind::Empty => "cannot parse integer from empty string",
4458 IntErrorKind::InvalidDigit => "invalid digit found in string",
4459 IntErrorKind::Overflow => "number too large to fit in target type",
4460 IntErrorKind::Underflow => "number too small to fit in target type",
4465 #[stable(feature = "rust1", since = "1.0.0")]
4466 impl fmt::Display for ParseIntError {
4467 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4468 self.__description().fmt(f)
4472 #[stable(feature = "rust1", since = "1.0.0")]
4473 pub use num::dec2flt::ParseFloatError;
4475 // Conversion traits for primitive integer and float types
4476 // Conversions T -> T are covered by a blanket impl and therefore excluded
4477 // Some conversions from and to usize/isize are not implemented due to portability concerns
4478 macro_rules! impl_from {
4479 ($Small: ty, $Large: ty, #[$attr:meta]) => {
4481 impl From<$Small> for $Large {
4483 fn from(small: $Small) -> $Large {
4490 // Unsigned -> Unsigned
4491 impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4492 impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4493 impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4494 impl_from! { u8, u128, #[unstable(feature = "i128", issue = "35118")] }
4495 impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4496 impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4497 impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4498 impl_from! { u16, u128, #[unstable(feature = "i128", issue = "35118")] }
4499 impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4500 impl_from! { u32, u128, #[unstable(feature = "i128", issue = "35118")] }
4501 impl_from! { u64, u128, #[unstable(feature = "i128", issue = "35118")] }
4504 impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4505 impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4506 impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4507 impl_from! { i8, i128, #[unstable(feature = "i128", issue = "35118")] }
4508 impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4509 impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4510 impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4511 impl_from! { i16, i128, #[unstable(feature = "i128", issue = "35118")] }
4512 impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4513 impl_from! { i32, i128, #[unstable(feature = "i128", issue = "35118")] }
4514 impl_from! { i64, i128, #[unstable(feature = "i128", issue = "35118")] }
4516 // Unsigned -> Signed
4517 impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4518 impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4519 impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4520 impl_from! { u8, i128, #[unstable(feature = "i128", issue = "35118")] }
4521 impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4522 impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4523 impl_from! { u16, i128, #[unstable(feature = "i128", issue = "35118")] }
4524 impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4525 impl_from! { u32, i128, #[unstable(feature = "i128", issue = "35118")] }
4526 impl_from! { u64, i128, #[unstable(feature = "i128", issue = "35118")] }
4528 // Note: integers can only be represented with full precision in a float if
4529 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
4530 // Lossy float conversions are not implemented at this time.
4533 impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4534 impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4535 impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4536 impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4537 impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4539 // Unsigned -> Float
4540 impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4541 impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4542 impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4543 impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4544 impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4547 impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4549 static ASCII_LOWERCASE_MAP: [u8; 256] = [
4550 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4551 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4552 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4553 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4554 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4555 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4556 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4557 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4560 b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4561 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4562 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4565 b'[', b'\\', b']', b'^', b'_',
4566 b'`', b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4567 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4568 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4569 b'x', b'y', b'z', b'{', b'|', b'}', b'~', 0x7f,
4570 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4571 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4572 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4573 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4574 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4575 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4576 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4577 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4578 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4579 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4580 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4581 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4582 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4583 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4584 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4585 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4588 static ASCII_UPPERCASE_MAP: [u8; 256] = [
4589 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4590 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4591 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4592 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4593 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4594 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4595 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4596 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4597 b'@', b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4598 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4599 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4600 b'X', b'Y', b'Z', b'[', b'\\', b']', b'^', b'_',
4603 b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4604 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4605 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4608 b'{', b'|', b'}', b'~', 0x7f,
4609 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4610 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4611 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4612 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4613 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4614 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4615 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4616 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4617 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4618 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4619 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4620 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4621 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4622 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4623 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4624 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4627 enum AsciiCharacterClass {
4629 Cw, // control whitespace
4633 Lx, // lowercase hex digit
4635 Ux, // uppercase hex digit
4638 use self::AsciiCharacterClass::*;
4640 static ASCII_CHARACTER_CLASS: [AsciiCharacterClass; 128] = [
4641 // _0 _1 _2 _3 _4 _5 _6 _7 _8 _9 _a _b _c _d _e _f
4642 C, C, C, C, C, C, C, C, C, Cw,Cw,C, Cw,Cw,C, C, // 0_
4643 C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, // 1_
4644 W, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, // 2_
4645 D, D, D, D, D, D, D, D, D, D, P, P, P, P, P, P, // 3_
4646 P, Ux,Ux,Ux,Ux,Ux,Ux,U, U, U, U, U, U, U, U, U, // 4_
4647 U, U, U, U, U, U, U, U, U, U, U, P, P, P, P, P, // 5_
4648 P, Lx,Lx,Lx,Lx,Lx,Lx,L, L, L, L, L, L, L, L, L, // 6_
4649 L, L, L, L, L, L, L, L, L, L, L, P, P, P, P, C, // 7_