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)`,
638 returning `None` if `rhs == 0` or the division results in overflow.
645 #![feature(euclidean_division)]
646 assert_eq!((", stringify!($SelfT),
647 "::min_value() + 1).checked_div_euc(-1), Some(", stringify!($Max), "));
648 assert_eq!(", stringify!($SelfT), "::min_value().checked_div_euc(-1), None);
649 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(euclidean_division)]
699 use std::", stringify!($SelfT), ";
701 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(2), Some(1));
702 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(0), None);
703 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)`,
1051 wrapping around at the 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 #![feature(euclidean_division)]
1067 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euc(10), 10);
1068 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(euclidean_division)]
1123 assert_eq!(100", stringify!($SelfT), ".wrapping_mod_euc(10), 0);
1124 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(euclidean_division)]
1414 use std::", stringify!($SelfT), ";
1416 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euc(2), (2, false));
1417 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 remainder `self.mod_euc(rhs)` by Euclidean division.
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(euclidean_division)]
1480 use std::", stringify!($SelfT), ";
1482 assert_eq!(5", stringify!($SelfT), ".overflowing_mod_euc(2), (1, false));
1483 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(euclidean_division)]
1708 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1711 assert_eq!(a.div_euc(b), 1); // 7 >= 4 * 1
1712 assert_eq!(a.div_euc(-b), -1); // 7 >= -4 * -1
1713 assert_eq!((-a).div_euc(b), -2); // -7 >= 4 * -2
1714 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 remainder `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(euclidean_division)]
1744 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1747 assert_eq!(a.mod_euc(b), 3);
1748 assert_eq!((-a).mod_euc(b), 1);
1749 assert_eq!(a.mod_euc(-b), 3);
1750 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(euclidean_division)]
2366 assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2367 assert_eq!(1", stringify!($SelfT), ".checked_div_euc(0), None);
2369 #[unstable(feature = "euclidean_division", issue = "49048")]
2371 pub fn checked_div_euc(self, rhs: Self) -> Option<Self> {
2375 Some(self.div_euc(rhs))
2382 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
2390 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
2391 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
2393 #[stable(feature = "wrapping", since = "1.7.0")]
2395 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
2399 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
2405 concat!("Checked Euclidean modulo. Computes `self.mod_euc(rhs)`, returning `None`
2413 #![feature(euclidean_division)]
2414 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(2), Some(1));
2415 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(0), None);
2417 #[unstable(feature = "euclidean_division", issue = "49048")]
2419 pub fn checked_mod_euc(self, rhs: Self) -> Option<Self> {
2423 Some(self.mod_euc(rhs))
2429 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
2432 Note that negating any positive integer will overflow.
2439 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
2440 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
2442 #[stable(feature = "wrapping", since = "1.7.0")]
2444 pub fn checked_neg(self) -> Option<Self> {
2445 let (a, b) = self.overflowing_neg();
2446 if b {None} else {Some(a)}
2451 concat!("Checked shift left. Computes `self << rhs`, returning `None`
2452 if `rhs` is larger than or equal to the number of bits in `self`.
2459 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
2460 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
2462 #[stable(feature = "wrapping", since = "1.7.0")]
2464 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
2465 let (a, b) = self.overflowing_shl(rhs);
2466 if b {None} else {Some(a)}
2471 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
2472 if `rhs` is larger than or equal to the number of bits in `self`.
2479 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
2480 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
2482 #[stable(feature = "wrapping", since = "1.7.0")]
2484 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
2485 let (a, b) = self.overflowing_shr(rhs);
2486 if b {None} else {Some(a)}
2491 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
2499 #![feature(no_panic_pow)]
2500 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
2501 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, "
2503 #[unstable(feature = "no_panic_pow", issue = "48320")]
2505 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
2506 let mut base = self;
2507 let mut acc: Self = 1;
2511 acc = acc.checked_mul(base)?;
2514 base = base.checked_mul(base)?;
2517 // Deal with the final bit of the exponent separately, since
2518 // squaring the base afterwards is not necessary and may cause a
2519 // needless overflow.
2521 acc = acc.checked_mul(base)?;
2529 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
2530 the numeric bounds instead of overflowing.
2537 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
2538 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
2540 #[stable(feature = "rust1", since = "1.0.0")]
2542 pub fn saturating_add(self, rhs: Self) -> Self {
2543 match self.checked_add(rhs) {
2545 None => Self::max_value(),
2551 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
2552 at the numeric bounds instead of overflowing.
2559 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
2560 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
2562 #[stable(feature = "rust1", since = "1.0.0")]
2564 pub fn saturating_sub(self, rhs: Self) -> Self {
2565 match self.checked_sub(rhs) {
2567 None => Self::min_value(),
2573 concat!("Saturating integer multiplication. Computes `self * rhs`,
2574 saturating at the numeric bounds instead of overflowing.
2581 ", $Feature, "use std::", stringify!($SelfT), ";
2583 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
2584 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
2585 "::MAX);", $EndFeature, "
2587 #[stable(feature = "wrapping", since = "1.7.0")]
2589 pub fn saturating_mul(self, rhs: Self) -> Self {
2590 self.checked_mul(rhs).unwrap_or(Self::max_value())
2595 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
2596 saturating at the numeric bounds instead of overflowing.
2603 #![feature(no_panic_pow)]
2604 ", $Feature, "use std::", stringify!($SelfT), ";
2606 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
2607 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
2610 #[unstable(feature = "no_panic_pow", issue = "48320")]
2612 pub fn saturating_pow(self, exp: u32) -> Self {
2613 match self.checked_pow(exp) {
2615 None => Self::max_value(),
2621 concat!("Wrapping (modular) addition. Computes `self + rhs`,
2622 wrapping around at the boundary of the type.
2629 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
2630 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
2633 #[stable(feature = "rust1", since = "1.0.0")]
2635 pub fn wrapping_add(self, rhs: Self) -> Self {
2637 intrinsics::overflowing_add(self, rhs)
2643 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
2644 wrapping around at the boundary of the type.
2651 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
2652 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
2655 #[stable(feature = "rust1", since = "1.0.0")]
2657 pub fn wrapping_sub(self, rhs: Self) -> Self {
2659 intrinsics::overflowing_sub(self, rhs)
2664 /// Wrapping (modular) multiplication. Computes `self *
2665 /// rhs`, wrapping around at the boundary of the type.
2671 /// Please note that this example is shared between integer types.
2672 /// Which explains why `u8` is used here.
2675 /// assert_eq!(10u8.wrapping_mul(12), 120);
2676 /// assert_eq!(25u8.wrapping_mul(12), 44);
2678 #[stable(feature = "rust1", since = "1.0.0")]
2680 pub fn wrapping_mul(self, rhs: Self) -> Self {
2682 intrinsics::overflowing_mul(self, rhs)
2687 concat!("Wrapping (modular) division. Computes `self / rhs`.
2688 Wrapped division on unsigned types is just normal division.
2689 There's no way wrapping could ever happen.
2690 This function exists, so that all operations
2691 are accounted for in the wrapping operations.
2698 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
2700 #[stable(feature = "num_wrapping", since = "1.2.0")]
2702 pub fn wrapping_div(self, rhs: Self) -> Self {
2708 concat!("Wrapping Euclidean division. Computes `self.div_euc(rhs)`.
2709 Wrapped division on unsigned types is just normal division.
2710 There's no way wrapping could ever happen.
2711 This function exists, so that all operations
2712 are accounted for in the wrapping operations.
2719 #![feature(euclidean_division)]
2720 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euc(10), 10);
2722 #[unstable(feature = "euclidean_division", issue = "49048")]
2724 pub fn wrapping_div_euc(self, rhs: Self) -> Self {
2730 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
2731 Wrapped remainder calculation on unsigned types is
2732 just the regular remainder calculation.
2733 There's no way wrapping could ever happen.
2734 This function exists, so that all operations
2735 are accounted for in the wrapping operations.
2742 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
2744 #[stable(feature = "num_wrapping", since = "1.2.0")]
2746 pub fn wrapping_rem(self, rhs: Self) -> Self {
2752 concat!("Wrapping Euclidean modulo. Computes `self.mod_euc(rhs)`.
2753 Wrapped modulo calculation on unsigned types is
2754 just the regular remainder calculation.
2755 There's no way wrapping could ever happen.
2756 This function exists, so that all operations
2757 are accounted for in the wrapping operations.
2764 #![feature(euclidean_division)]
2765 assert_eq!(100", stringify!($SelfT), ".wrapping_mod_euc(10), 0);
2767 #[unstable(feature = "euclidean_division", issue = "49048")]
2769 pub fn wrapping_mod_euc(self, rhs: Self) -> Self {
2774 /// Wrapping (modular) negation. Computes `-self`,
2775 /// wrapping around at the boundary of the type.
2777 /// Since unsigned types do not have negative equivalents
2778 /// all applications of this function will wrap (except for `-0`).
2779 /// For values smaller than the corresponding signed type's maximum
2780 /// the result is the same as casting the corresponding signed value.
2781 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
2782 /// `MAX` is the corresponding signed type's maximum.
2788 /// Please note that this example is shared between integer types.
2789 /// Which explains why `i8` is used here.
2792 /// assert_eq!(100i8.wrapping_neg(), -100);
2793 /// assert_eq!((-128i8).wrapping_neg(), -128);
2795 #[stable(feature = "num_wrapping", since = "1.2.0")]
2797 pub fn wrapping_neg(self) -> Self {
2798 self.overflowing_neg().0
2802 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
2803 where `mask` removes any high-order bits of `rhs` that
2804 would cause the shift to exceed the bitwidth of the type.
2806 Note that this is *not* the same as a rotate-left; the
2807 RHS of a wrapping shift-left is restricted to the range
2808 of the type, rather than the bits shifted out of the LHS
2809 being returned to the other end. The primitive integer
2810 types all implement a `rotate_left` function, which may
2811 be what you want instead.
2818 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
2819 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
2821 #[stable(feature = "num_wrapping", since = "1.2.0")]
2823 pub fn wrapping_shl(self, rhs: u32) -> Self {
2825 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
2831 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
2832 where `mask` removes any high-order bits of `rhs` that
2833 would cause the shift to exceed the bitwidth of the type.
2835 Note that this is *not* the same as a rotate-right; the
2836 RHS of a wrapping shift-right is restricted to the range
2837 of the type, rather than the bits shifted out of the LHS
2838 being returned to the other end. The primitive integer
2839 types all implement a `rotate_right` function, which may
2840 be what you want instead.
2847 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
2848 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
2850 #[stable(feature = "num_wrapping", since = "1.2.0")]
2852 pub fn wrapping_shr(self, rhs: u32) -> Self {
2854 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
2860 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
2861 wrapping around at the boundary of the type.
2868 #![feature(no_panic_pow)]
2869 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
2870 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
2872 #[unstable(feature = "no_panic_pow", issue = "48320")]
2874 pub fn wrapping_pow(self, mut exp: u32) -> Self {
2875 let mut base = self;
2876 let mut acc: Self = 1;
2880 acc = acc.wrapping_mul(base);
2883 base = base.wrapping_mul(base);
2886 // Deal with the final bit of the exponent separately, since
2887 // squaring the base afterwards is not necessary and may cause a
2888 // needless overflow.
2890 acc = acc.wrapping_mul(base);
2898 concat!("Calculates `self` + `rhs`
2900 Returns a tuple of the addition along with a boolean indicating
2901 whether an arithmetic overflow would occur. If an overflow would
2902 have occurred then the wrapped value is returned.
2909 ", $Feature, "use std::", stringify!($SelfT), ";
2911 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
2912 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
2915 #[stable(feature = "wrapping", since = "1.7.0")]
2916 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
2917 let (a, b) = unsafe {
2918 intrinsics::add_with_overflow(self as $ActualT,
2926 concat!("Calculates `self` - `rhs`
2928 Returns a tuple of the subtraction along with a boolean indicating
2929 whether an arithmetic overflow would occur. If an overflow would
2930 have occurred then the wrapped value is returned.
2937 ", $Feature, "use std::", stringify!($SelfT), ";
2939 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
2940 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
2944 #[stable(feature = "wrapping", since = "1.7.0")]
2945 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
2946 let (a, b) = unsafe {
2947 intrinsics::sub_with_overflow(self as $ActualT,
2954 /// Calculates the multiplication of `self` and `rhs`.
2956 /// Returns a tuple of the multiplication along with a boolean
2957 /// indicating whether an arithmetic overflow would occur. If an
2958 /// overflow would have occurred then the wrapped value is returned.
2964 /// Please note that this example is shared between integer types.
2965 /// Which explains why `u32` is used here.
2968 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
2969 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
2972 #[stable(feature = "wrapping", since = "1.7.0")]
2973 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
2974 let (a, b) = unsafe {
2975 intrinsics::mul_with_overflow(self as $ActualT,
2982 concat!("Calculates the divisor when `self` is divided by `rhs`.
2984 Returns a tuple of the divisor along with a boolean indicating
2985 whether an arithmetic overflow would occur. Note that for unsigned
2986 integers overflow never occurs, so the second value is always
2991 This function will panic if `rhs` is 0.
2998 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
3001 #[stable(feature = "wrapping", since = "1.7.0")]
3002 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3008 concat!("Calculates the quotient of Euclidean division `self.div_euc(rhs)`.
3010 Returns a tuple of the divisor along with a boolean indicating
3011 whether an arithmetic overflow would occur. Note that for unsigned
3012 integers overflow never occurs, so the second value is always
3017 This function will panic if `rhs` is 0.
3024 #![feature(euclidean_division)]
3025 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euc(2), (2, false));
3028 #[unstable(feature = "euclidean_division", issue = "49048")]
3029 pub fn overflowing_div_euc(self, rhs: Self) -> (Self, bool) {
3035 concat!("Calculates the remainder when `self` is divided by `rhs`.
3037 Returns a tuple of the remainder after dividing along with a boolean
3038 indicating whether an arithmetic overflow would occur. Note that for
3039 unsigned integers overflow never occurs, so the second value is
3044 This function will panic if `rhs` is 0.
3051 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3054 #[stable(feature = "wrapping", since = "1.7.0")]
3055 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3061 concat!("Calculates the remainder `self.mod_euc(rhs)` by Euclidean division.
3063 Returns a tuple of the modulo after dividing along with a boolean
3064 indicating whether an arithmetic overflow would occur. Note that for
3065 unsigned integers overflow never occurs, so the second value is
3070 This function will panic if `rhs` is 0.
3077 #![feature(euclidean_division)]
3078 assert_eq!(5", stringify!($SelfT), ".overflowing_mod_euc(2), (1, false));
3081 #[unstable(feature = "euclidean_division", issue = "49048")]
3082 pub fn overflowing_mod_euc(self, rhs: Self) -> (Self, bool) {
3088 concat!("Negates self in an overflowing fashion.
3090 Returns `!self + 1` using wrapping operations to return the value
3091 that represents the negation of this unsigned value. Note that for
3092 positive unsigned values overflow always occurs, but negating 0 does
3100 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3101 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3102 ", true));", $EndFeature, "
3105 #[stable(feature = "wrapping", since = "1.7.0")]
3106 pub fn overflowing_neg(self) -> (Self, bool) {
3107 ((!self).wrapping_add(1), self != 0)
3112 concat!("Shifts self left by `rhs` bits.
3114 Returns a tuple of the shifted version of self along with a boolean
3115 indicating whether the shift value was larger than or equal to the
3116 number of bits. If the shift value is too large, then value is
3117 masked (N-1) where N is the number of bits, and this value is then
3118 used to perform the shift.
3125 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3126 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3129 #[stable(feature = "wrapping", since = "1.7.0")]
3130 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3131 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3136 concat!("Shifts self right by `rhs` bits.
3138 Returns a tuple of the shifted version of self along with a boolean
3139 indicating whether the shift value was larger than or equal to the
3140 number of bits. If the shift value is too large, then value is
3141 masked (N-1) where N is the number of bits, and this value is then
3142 used to perform the shift.
3149 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
3150 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
3153 #[stable(feature = "wrapping", since = "1.7.0")]
3154 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3155 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
3160 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3162 Returns a tuple of the exponentiation along with a bool indicating
3163 whether an overflow happened.
3170 #![feature(no_panic_pow)]
3171 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
3172 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
3174 #[unstable(feature = "no_panic_pow", issue = "48320")]
3176 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3177 let mut base = self;
3178 let mut acc: Self = 1;
3179 let mut overflown = false;
3180 // Scratch space for storing results of overflowing_mul.
3185 r = acc.overflowing_mul(base);
3190 r = base.overflowing_mul(base);
3195 // Deal with the final bit of the exponent separately, since
3196 // squaring the base afterwards is not necessary and may cause a
3197 // needless overflow.
3199 r = acc.overflowing_mul(base);
3209 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3216 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
3218 #[stable(feature = "rust1", since = "1.0.0")]
3220 #[rustc_inherit_overflow_checks]
3221 pub fn pow(self, mut exp: u32) -> Self {
3222 let mut base = self;
3233 // Deal with the final bit of the exponent separately, since
3234 // squaring the base afterwards is not necessary and may cause a
3235 // needless overflow.
3245 concat!("Performs Euclidean division.
3247 For unsigned types, this is just the same as `self / rhs`.
3254 #![feature(euclidean_division)]
3255 assert_eq!(7", stringify!($SelfT), ".div_euc(4), 1); // or any other integer type
3257 #[unstable(feature = "euclidean_division", issue = "49048")]
3259 #[rustc_inherit_overflow_checks]
3260 pub fn div_euc(self, rhs: Self) -> Self {
3267 concat!("Calculates the remainder `self mod rhs` by Euclidean division.
3269 For unsigned types, this is just the same as `self % rhs`.
3276 #![feature(euclidean_division)]
3277 assert_eq!(7", stringify!($SelfT), ".mod_euc(4), 3); // or any other integer type
3279 #[unstable(feature = "euclidean_division", issue = "49048")]
3281 #[rustc_inherit_overflow_checks]
3282 pub fn mod_euc(self, rhs: Self) -> Self {
3288 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
3295 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
3296 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
3298 #[stable(feature = "rust1", since = "1.0.0")]
3300 pub fn is_power_of_two(self) -> bool {
3301 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
3305 // Returns one less than next power of two.
3306 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
3308 // 8u8.one_less_than_next_power_of_two() == 7
3309 // 6u8.one_less_than_next_power_of_two() == 7
3311 // This method cannot overflow, as in the `next_power_of_two`
3312 // overflow cases it instead ends up returning the maximum value
3313 // of the type, and can return 0 for 0.
3315 fn one_less_than_next_power_of_two(self) -> Self {
3316 if self <= 1 { return 0; }
3318 // Because `p > 0`, it cannot consist entirely of leading zeros.
3319 // That means the shift is always in-bounds, and some processors
3320 // (such as intel pre-haswell) have more efficient ctlz
3321 // intrinsics when the argument is non-zero.
3323 let z = unsafe { intrinsics::ctlz_nonzero(p) };
3324 <$SelfT>::max_value() >> z
3328 concat!("Returns the smallest power of two greater than or equal to `self`.
3330 When return value overflows (i.e. `self > (1 << (N-1))` for type
3331 `uN`), it panics in debug mode and return value is wrapped to 0 in
3332 release mode (the only situation in which method can return 0).
3339 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
3340 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
3342 #[stable(feature = "rust1", since = "1.0.0")]
3344 pub fn next_power_of_two(self) -> Self {
3345 // Call the trait to get overflow checks
3346 ops::Add::add(self.one_less_than_next_power_of_two(), 1)
3351 concat!("Returns the smallest power of two greater than or equal to `n`. If
3352 the next power of two is greater than the type's maximum value,
3353 `None` is returned, otherwise the power of two is wrapped in `Some`.
3360 ", $Feature, "assert_eq!(2", stringify!($SelfT),
3361 ".checked_next_power_of_two(), Some(2));
3362 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
3363 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
3366 #[stable(feature = "rust1", since = "1.0.0")]
3367 pub fn checked_next_power_of_two(self) -> Option<Self> {
3368 self.one_less_than_next_power_of_two().checked_add(1)
3376 uint_impl! { u8, u8, 8, 255, "", "" }
3379 /// Checks if the value is within the ASCII range.
3384 /// let ascii = 97u8;
3385 /// let non_ascii = 150u8;
3387 /// assert!(ascii.is_ascii());
3388 /// assert!(!non_ascii.is_ascii());
3390 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3392 pub fn is_ascii(&self) -> bool {
3396 /// Makes a copy of the value in its ASCII upper case equivalent.
3398 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3399 /// but non-ASCII letters are unchanged.
3401 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
3406 /// let lowercase_a = 97u8;
3408 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
3411 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
3412 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3414 pub fn to_ascii_uppercase(&self) -> u8 {
3415 ASCII_UPPERCASE_MAP[*self as usize]
3418 /// Makes a copy of the value in its ASCII lower case equivalent.
3420 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3421 /// but non-ASCII letters are unchanged.
3423 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
3428 /// let uppercase_a = 65u8;
3430 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
3433 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
3434 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3436 pub fn to_ascii_lowercase(&self) -> u8 {
3437 ASCII_LOWERCASE_MAP[*self as usize]
3440 /// Checks that two values are an ASCII case-insensitive match.
3442 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
3447 /// let lowercase_a = 97u8;
3448 /// let uppercase_a = 65u8;
3450 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
3452 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3454 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
3455 self.to_ascii_lowercase() == other.to_ascii_lowercase()
3458 /// Converts this value to its ASCII upper case equivalent in-place.
3460 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3461 /// but non-ASCII letters are unchanged.
3463 /// To return a new uppercased value without modifying the existing one, use
3464 /// [`to_ascii_uppercase`].
3469 /// let mut byte = b'a';
3471 /// byte.make_ascii_uppercase();
3473 /// assert_eq!(b'A', byte);
3476 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
3477 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3479 pub fn make_ascii_uppercase(&mut self) {
3480 *self = self.to_ascii_uppercase();
3483 /// Converts this value to its ASCII lower case equivalent in-place.
3485 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3486 /// but non-ASCII letters are unchanged.
3488 /// To return a new lowercased value without modifying the existing one, use
3489 /// [`to_ascii_lowercase`].
3494 /// let mut byte = b'A';
3496 /// byte.make_ascii_lowercase();
3498 /// assert_eq!(b'a', byte);
3501 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
3502 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3504 pub fn make_ascii_lowercase(&mut self) {
3505 *self = self.to_ascii_lowercase();
3508 /// Checks if the value is an ASCII alphabetic character:
3510 /// - U+0041 'A' ... U+005A 'Z', or
3511 /// - U+0061 'a' ... U+007A 'z'.
3516 /// #![feature(ascii_ctype)]
3518 /// let uppercase_a = b'A';
3519 /// let uppercase_g = b'G';
3522 /// let zero = b'0';
3523 /// let percent = b'%';
3524 /// let space = b' ';
3526 /// let esc = 0x1b_u8;
3528 /// assert!(uppercase_a.is_ascii_alphabetic());
3529 /// assert!(uppercase_g.is_ascii_alphabetic());
3530 /// assert!(a.is_ascii_alphabetic());
3531 /// assert!(g.is_ascii_alphabetic());
3532 /// assert!(!zero.is_ascii_alphabetic());
3533 /// assert!(!percent.is_ascii_alphabetic());
3534 /// assert!(!space.is_ascii_alphabetic());
3535 /// assert!(!lf.is_ascii_alphabetic());
3536 /// assert!(!esc.is_ascii_alphabetic());
3538 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3540 pub fn is_ascii_alphabetic(&self) -> bool {
3541 if *self >= 0x80 { return false; }
3542 match ASCII_CHARACTER_CLASS[*self as usize] {
3543 L | Lx | U | Ux => true,
3548 /// Checks if the value is an ASCII uppercase character:
3549 /// U+0041 'A' ... U+005A 'Z'.
3554 /// #![feature(ascii_ctype)]
3556 /// let uppercase_a = b'A';
3557 /// let uppercase_g = b'G';
3560 /// let zero = b'0';
3561 /// let percent = b'%';
3562 /// let space = b' ';
3564 /// let esc = 0x1b_u8;
3566 /// assert!(uppercase_a.is_ascii_uppercase());
3567 /// assert!(uppercase_g.is_ascii_uppercase());
3568 /// assert!(!a.is_ascii_uppercase());
3569 /// assert!(!g.is_ascii_uppercase());
3570 /// assert!(!zero.is_ascii_uppercase());
3571 /// assert!(!percent.is_ascii_uppercase());
3572 /// assert!(!space.is_ascii_uppercase());
3573 /// assert!(!lf.is_ascii_uppercase());
3574 /// assert!(!esc.is_ascii_uppercase());
3576 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3578 pub fn is_ascii_uppercase(&self) -> bool {
3579 if *self >= 0x80 { return false }
3580 match ASCII_CHARACTER_CLASS[*self as usize] {
3586 /// Checks if the value is an ASCII lowercase character:
3587 /// U+0061 'a' ... U+007A 'z'.
3592 /// #![feature(ascii_ctype)]
3594 /// let uppercase_a = b'A';
3595 /// let uppercase_g = b'G';
3598 /// let zero = b'0';
3599 /// let percent = b'%';
3600 /// let space = b' ';
3602 /// let esc = 0x1b_u8;
3604 /// assert!(!uppercase_a.is_ascii_lowercase());
3605 /// assert!(!uppercase_g.is_ascii_lowercase());
3606 /// assert!(a.is_ascii_lowercase());
3607 /// assert!(g.is_ascii_lowercase());
3608 /// assert!(!zero.is_ascii_lowercase());
3609 /// assert!(!percent.is_ascii_lowercase());
3610 /// assert!(!space.is_ascii_lowercase());
3611 /// assert!(!lf.is_ascii_lowercase());
3612 /// assert!(!esc.is_ascii_lowercase());
3614 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3616 pub fn is_ascii_lowercase(&self) -> bool {
3617 if *self >= 0x80 { return false }
3618 match ASCII_CHARACTER_CLASS[*self as usize] {
3624 /// Checks if the value is an ASCII alphanumeric character:
3626 /// - U+0041 'A' ... U+005A 'Z', or
3627 /// - U+0061 'a' ... U+007A 'z', or
3628 /// - U+0030 '0' ... U+0039 '9'.
3633 /// #![feature(ascii_ctype)]
3635 /// let uppercase_a = b'A';
3636 /// let uppercase_g = b'G';
3639 /// let zero = b'0';
3640 /// let percent = b'%';
3641 /// let space = b' ';
3643 /// let esc = 0x1b_u8;
3645 /// assert!(uppercase_a.is_ascii_alphanumeric());
3646 /// assert!(uppercase_g.is_ascii_alphanumeric());
3647 /// assert!(a.is_ascii_alphanumeric());
3648 /// assert!(g.is_ascii_alphanumeric());
3649 /// assert!(zero.is_ascii_alphanumeric());
3650 /// assert!(!percent.is_ascii_alphanumeric());
3651 /// assert!(!space.is_ascii_alphanumeric());
3652 /// assert!(!lf.is_ascii_alphanumeric());
3653 /// assert!(!esc.is_ascii_alphanumeric());
3655 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3657 pub fn is_ascii_alphanumeric(&self) -> bool {
3658 if *self >= 0x80 { return false }
3659 match ASCII_CHARACTER_CLASS[*self as usize] {
3660 D | L | Lx | U | Ux => true,
3665 /// Checks if the value is an ASCII decimal digit:
3666 /// U+0030 '0' ... U+0039 '9'.
3671 /// #![feature(ascii_ctype)]
3673 /// let uppercase_a = b'A';
3674 /// let uppercase_g = b'G';
3677 /// let zero = b'0';
3678 /// let percent = b'%';
3679 /// let space = b' ';
3681 /// let esc = 0x1b_u8;
3683 /// assert!(!uppercase_a.is_ascii_digit());
3684 /// assert!(!uppercase_g.is_ascii_digit());
3685 /// assert!(!a.is_ascii_digit());
3686 /// assert!(!g.is_ascii_digit());
3687 /// assert!(zero.is_ascii_digit());
3688 /// assert!(!percent.is_ascii_digit());
3689 /// assert!(!space.is_ascii_digit());
3690 /// assert!(!lf.is_ascii_digit());
3691 /// assert!(!esc.is_ascii_digit());
3693 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3695 pub fn is_ascii_digit(&self) -> bool {
3696 if *self >= 0x80 { return false }
3697 match ASCII_CHARACTER_CLASS[*self as usize] {
3703 /// Checks if the value is an ASCII hexadecimal digit:
3705 /// - U+0030 '0' ... U+0039 '9', or
3706 /// - U+0041 'A' ... U+0046 'F', or
3707 /// - U+0061 'a' ... U+0066 'f'.
3712 /// #![feature(ascii_ctype)]
3714 /// let uppercase_a = b'A';
3715 /// let uppercase_g = b'G';
3718 /// let zero = b'0';
3719 /// let percent = b'%';
3720 /// let space = b' ';
3722 /// let esc = 0x1b_u8;
3724 /// assert!(uppercase_a.is_ascii_hexdigit());
3725 /// assert!(!uppercase_g.is_ascii_hexdigit());
3726 /// assert!(a.is_ascii_hexdigit());
3727 /// assert!(!g.is_ascii_hexdigit());
3728 /// assert!(zero.is_ascii_hexdigit());
3729 /// assert!(!percent.is_ascii_hexdigit());
3730 /// assert!(!space.is_ascii_hexdigit());
3731 /// assert!(!lf.is_ascii_hexdigit());
3732 /// assert!(!esc.is_ascii_hexdigit());
3734 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3736 pub fn is_ascii_hexdigit(&self) -> bool {
3737 if *self >= 0x80 { return false }
3738 match ASCII_CHARACTER_CLASS[*self as usize] {
3739 D | Lx | Ux => true,
3744 /// Checks if the value is an ASCII punctuation character:
3746 /// - U+0021 ... U+002F `! " # $ % & ' ( ) * + , - . /`, or
3747 /// - U+003A ... U+0040 `: ; < = > ? @`, or
3748 /// - U+005B ... U+0060 ``[ \ ] ^ _ ` ``, or
3749 /// - U+007B ... U+007E `{ | } ~`
3754 /// #![feature(ascii_ctype)]
3756 /// let uppercase_a = b'A';
3757 /// let uppercase_g = b'G';
3760 /// let zero = b'0';
3761 /// let percent = b'%';
3762 /// let space = b' ';
3764 /// let esc = 0x1b_u8;
3766 /// assert!(!uppercase_a.is_ascii_punctuation());
3767 /// assert!(!uppercase_g.is_ascii_punctuation());
3768 /// assert!(!a.is_ascii_punctuation());
3769 /// assert!(!g.is_ascii_punctuation());
3770 /// assert!(!zero.is_ascii_punctuation());
3771 /// assert!(percent.is_ascii_punctuation());
3772 /// assert!(!space.is_ascii_punctuation());
3773 /// assert!(!lf.is_ascii_punctuation());
3774 /// assert!(!esc.is_ascii_punctuation());
3776 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3778 pub fn is_ascii_punctuation(&self) -> bool {
3779 if *self >= 0x80 { return false }
3780 match ASCII_CHARACTER_CLASS[*self as usize] {
3786 /// Checks if the value is an ASCII graphic character:
3787 /// U+0021 '!' ... U+007E '~'.
3792 /// #![feature(ascii_ctype)]
3794 /// let uppercase_a = b'A';
3795 /// let uppercase_g = b'G';
3798 /// let zero = b'0';
3799 /// let percent = b'%';
3800 /// let space = b' ';
3802 /// let esc = 0x1b_u8;
3804 /// assert!(uppercase_a.is_ascii_graphic());
3805 /// assert!(uppercase_g.is_ascii_graphic());
3806 /// assert!(a.is_ascii_graphic());
3807 /// assert!(g.is_ascii_graphic());
3808 /// assert!(zero.is_ascii_graphic());
3809 /// assert!(percent.is_ascii_graphic());
3810 /// assert!(!space.is_ascii_graphic());
3811 /// assert!(!lf.is_ascii_graphic());
3812 /// assert!(!esc.is_ascii_graphic());
3814 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3816 pub fn is_ascii_graphic(&self) -> bool {
3817 if *self >= 0x80 { return false; }
3818 match ASCII_CHARACTER_CLASS[*self as usize] {
3819 Ux | U | Lx | L | D | P => true,
3824 /// Checks if the value is an ASCII whitespace character:
3825 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
3826 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
3828 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
3829 /// whitespace][infra-aw]. There are several other definitions in
3830 /// wide use. For instance, [the POSIX locale][pct] includes
3831 /// U+000B VERTICAL TAB as well as all the above characters,
3832 /// but—from the very same specification—[the default rule for
3833 /// "field splitting" in the Bourne shell][bfs] considers *only*
3834 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
3836 /// If you are writing a program that will process an existing
3837 /// file format, check what that format's definition of whitespace is
3838 /// before using this function.
3840 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
3841 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
3842 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
3847 /// #![feature(ascii_ctype)]
3849 /// let uppercase_a = b'A';
3850 /// let uppercase_g = b'G';
3853 /// let zero = b'0';
3854 /// let percent = b'%';
3855 /// let space = b' ';
3857 /// let esc = 0x1b_u8;
3859 /// assert!(!uppercase_a.is_ascii_whitespace());
3860 /// assert!(!uppercase_g.is_ascii_whitespace());
3861 /// assert!(!a.is_ascii_whitespace());
3862 /// assert!(!g.is_ascii_whitespace());
3863 /// assert!(!zero.is_ascii_whitespace());
3864 /// assert!(!percent.is_ascii_whitespace());
3865 /// assert!(space.is_ascii_whitespace());
3866 /// assert!(lf.is_ascii_whitespace());
3867 /// assert!(!esc.is_ascii_whitespace());
3869 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3871 pub fn is_ascii_whitespace(&self) -> bool {
3872 if *self >= 0x80 { return false; }
3873 match ASCII_CHARACTER_CLASS[*self as usize] {
3879 /// Checks if the value is an ASCII control character:
3880 /// U+0000 NUL ... U+001F UNIT SEPARATOR, or U+007F DELETE.
3881 /// Note that most ASCII whitespace characters are control
3882 /// characters, but SPACE is not.
3887 /// #![feature(ascii_ctype)]
3889 /// let uppercase_a = b'A';
3890 /// let uppercase_g = b'G';
3893 /// let zero = b'0';
3894 /// let percent = b'%';
3895 /// let space = b' ';
3897 /// let esc = 0x1b_u8;
3899 /// assert!(!uppercase_a.is_ascii_control());
3900 /// assert!(!uppercase_g.is_ascii_control());
3901 /// assert!(!a.is_ascii_control());
3902 /// assert!(!g.is_ascii_control());
3903 /// assert!(!zero.is_ascii_control());
3904 /// assert!(!percent.is_ascii_control());
3905 /// assert!(!space.is_ascii_control());
3906 /// assert!(lf.is_ascii_control());
3907 /// assert!(esc.is_ascii_control());
3909 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3911 pub fn is_ascii_control(&self) -> bool {
3912 if *self >= 0x80 { return false; }
3913 match ASCII_CHARACTER_CLASS[*self as usize] {
3922 uint_impl! { u16, u16, 16, 65535, "", "" }
3927 uint_impl! { u32, u32, 32, 4294967295, "", "" }
3932 uint_impl! { u64, u64, 64, 18446744073709551615, "", "" }
3937 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "#![feature(i128_type)]
3945 #[cfg(target_pointer_width = "16")]
3948 uint_impl! { usize, u16, 16, 65536, "", "" }
3950 #[cfg(target_pointer_width = "32")]
3953 uint_impl! { usize, u32, 32, 4294967295, "", "" }
3956 #[cfg(target_pointer_width = "64")]
3959 uint_impl! { usize, u64, 64, 18446744073709551615, "", "" }
3962 /// A classification of floating point numbers.
3964 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
3965 /// their documentation for more.
3967 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
3968 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
3973 /// use std::num::FpCategory;
3976 /// let num = 12.4_f32;
3977 /// let inf = f32::INFINITY;
3978 /// let zero = 0f32;
3979 /// let sub: f32 = 1.1754942e-38;
3980 /// let nan = f32::NAN;
3982 /// assert_eq!(num.classify(), FpCategory::Normal);
3983 /// assert_eq!(inf.classify(), FpCategory::Infinite);
3984 /// assert_eq!(zero.classify(), FpCategory::Zero);
3985 /// assert_eq!(nan.classify(), FpCategory::Nan);
3986 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
3988 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
3989 #[stable(feature = "rust1", since = "1.0.0")]
3990 pub enum FpCategory {
3991 /// "Not a Number", often obtained by dividing by zero.
3992 #[stable(feature = "rust1", since = "1.0.0")]
3995 /// Positive or negative infinity.
3996 #[stable(feature = "rust1", since = "1.0.0")]
3999 /// Positive or negative zero.
4000 #[stable(feature = "rust1", since = "1.0.0")]
4003 /// De-normalized floating point representation (less precise than `Normal`).
4004 #[stable(feature = "rust1", since = "1.0.0")]
4007 /// A regular floating point number.
4008 #[stable(feature = "rust1", since = "1.0.0")]
4012 /// A built-in floating point number.
4014 #[unstable(feature = "core_float",
4015 reason = "stable interface is via `impl f{32,64}` in later crates",
4017 pub trait Float: Sized {
4018 /// Type used by `to_bits` and `from_bits`.
4019 #[stable(feature = "core_float_bits", since = "1.25.0")]
4022 /// Returns `true` if this value is NaN and false otherwise.
4023 #[stable(feature = "core", since = "1.6.0")]
4024 fn is_nan(self) -> bool;
4025 /// Returns `true` if this value is positive infinity or negative infinity and
4026 /// false otherwise.
4027 #[stable(feature = "core", since = "1.6.0")]
4028 fn is_infinite(self) -> bool;
4029 /// Returns `true` if this number is neither infinite nor NaN.
4030 #[stable(feature = "core", since = "1.6.0")]
4031 fn is_finite(self) -> bool;
4032 /// Returns `true` if this number is neither zero, infinite, denormal, or NaN.
4033 #[stable(feature = "core", since = "1.6.0")]
4034 fn is_normal(self) -> bool;
4035 /// Returns the category that this number falls into.
4036 #[stable(feature = "core", since = "1.6.0")]
4037 fn classify(self) -> FpCategory;
4039 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
4040 /// number is `Float::nan()`.
4041 #[stable(feature = "core", since = "1.6.0")]
4042 fn abs(self) -> Self;
4043 /// Returns a number that represents the sign of `self`.
4045 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
4046 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
4047 /// - `Float::nan()` if the number is `Float::nan()`
4048 #[stable(feature = "core", since = "1.6.0")]
4049 fn signum(self) -> Self;
4051 /// Returns `true` if `self` is positive, including `+0.0` and
4052 /// `Float::infinity()`.
4053 #[stable(feature = "core", since = "1.6.0")]
4054 fn is_sign_positive(self) -> bool;
4055 /// Returns `true` if `self` is negative, including `-0.0` and
4056 /// `Float::neg_infinity()`.
4057 #[stable(feature = "core", since = "1.6.0")]
4058 fn is_sign_negative(self) -> bool;
4060 /// Take the reciprocal (inverse) of a number, `1/x`.
4061 #[stable(feature = "core", since = "1.6.0")]
4062 fn recip(self) -> Self;
4064 /// Raise a number to an integer power.
4066 /// Using this function is generally faster than using `powf`
4067 #[stable(feature = "core", since = "1.6.0")]
4068 fn powi(self, n: i32) -> Self;
4070 /// Convert radians to degrees.
4071 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
4072 fn to_degrees(self) -> Self;
4073 /// Convert degrees to radians.
4074 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
4075 fn to_radians(self) -> Self;
4077 /// Returns the maximum of the two numbers.
4078 #[stable(feature = "core_float_min_max", since="1.20.0")]
4079 fn max(self, other: Self) -> Self;
4080 /// Returns the minimum of the two numbers.
4081 #[stable(feature = "core_float_min_max", since="1.20.0")]
4082 fn min(self, other: Self) -> Self;
4084 /// Raw transmutation to integer.
4085 #[stable(feature = "core_float_bits", since="1.25.0")]
4086 fn to_bits(self) -> Self::Bits;
4087 /// Raw transmutation from integer.
4088 #[stable(feature = "core_float_bits", since="1.25.0")]
4089 fn from_bits(v: Self::Bits) -> Self;
4092 macro_rules! from_str_radix_int_impl {
4094 #[stable(feature = "rust1", since = "1.0.0")]
4095 impl FromStr for $t {
4096 type Err = ParseIntError;
4097 fn from_str(src: &str) -> Result<Self, ParseIntError> {
4098 from_str_radix(src, 10)
4103 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
4105 /// The error type returned when a checked integral type conversion fails.
4106 #[unstable(feature = "try_from", issue = "33417")]
4107 #[derive(Debug, Copy, Clone)]
4108 pub struct TryFromIntError(());
4110 impl TryFromIntError {
4111 #[unstable(feature = "int_error_internals",
4112 reason = "available through Error trait and this method should \
4113 not be exposed publicly",
4116 pub fn __description(&self) -> &str {
4117 "out of range integral type conversion attempted"
4121 #[unstable(feature = "try_from", issue = "33417")]
4122 impl fmt::Display for TryFromIntError {
4123 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4124 self.__description().fmt(fmt)
4128 #[unstable(feature = "try_from", issue = "33417")]
4129 impl From<!> for TryFromIntError {
4130 fn from(never: !) -> TryFromIntError {
4135 // no possible bounds violation
4136 macro_rules! try_from_unbounded {
4137 ($source:ty, $($target:ty),*) => {$(
4138 #[unstable(feature = "try_from", issue = "33417")]
4139 impl TryFrom<$source> for $target {
4143 fn try_from(value: $source) -> Result<Self, Self::Error> {
4144 Ok(value as $target)
4150 // only negative bounds
4151 macro_rules! try_from_lower_bounded {
4152 ($source:ty, $($target:ty),*) => {$(
4153 #[unstable(feature = "try_from", issue = "33417")]
4154 impl TryFrom<$source> for $target {
4155 type Error = TryFromIntError;
4158 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4162 Err(TryFromIntError(()))
4169 // unsigned to signed (only positive bound)
4170 macro_rules! try_from_upper_bounded {
4171 ($source:ty, $($target:ty),*) => {$(
4172 #[unstable(feature = "try_from", issue = "33417")]
4173 impl TryFrom<$source> for $target {
4174 type Error = TryFromIntError;
4177 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4178 if u > (<$target>::max_value() as $source) {
4179 Err(TryFromIntError(()))
4189 macro_rules! try_from_both_bounded {
4190 ($source:ty, $($target:ty),*) => {$(
4191 #[unstable(feature = "try_from", issue = "33417")]
4192 impl TryFrom<$source> for $target {
4193 type Error = TryFromIntError;
4196 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4197 let min = <$target>::min_value() as $source;
4198 let max = <$target>::max_value() as $source;
4199 if u < min || u > max {
4200 Err(TryFromIntError(()))
4210 ($mac:ident, $source:ty, $($target:ty),*) => {$(
4211 $mac!($target, $source);
4215 /// intra-sign conversions
4216 try_from_upper_bounded!(u16, u8);
4217 try_from_upper_bounded!(u32, u16, u8);
4218 try_from_upper_bounded!(u64, u32, u16, u8);
4219 try_from_upper_bounded!(u128, u64, u32, u16, u8);
4221 try_from_both_bounded!(i16, i8);
4222 try_from_both_bounded!(i32, i16, i8);
4223 try_from_both_bounded!(i64, i32, i16, i8);
4224 try_from_both_bounded!(i128, i64, i32, i16, i8);
4226 // unsigned-to-signed
4227 try_from_upper_bounded!(u8, i8);
4228 try_from_upper_bounded!(u16, i8, i16);
4229 try_from_upper_bounded!(u32, i8, i16, i32);
4230 try_from_upper_bounded!(u64, i8, i16, i32, i64);
4231 try_from_upper_bounded!(u128, i8, i16, i32, i64, i128);
4233 // signed-to-unsigned
4234 try_from_lower_bounded!(i8, u8, u16, u32, u64, u128);
4235 try_from_lower_bounded!(i16, u16, u32, u64, u128);
4236 try_from_lower_bounded!(i32, u32, u64, u128);
4237 try_from_lower_bounded!(i64, u64, u128);
4238 try_from_lower_bounded!(i128, u128);
4239 try_from_both_bounded!(i16, u8);
4240 try_from_both_bounded!(i32, u16, u8);
4241 try_from_both_bounded!(i64, u32, u16, u8);
4242 try_from_both_bounded!(i128, u64, u32, u16, u8);
4245 try_from_upper_bounded!(usize, isize);
4246 try_from_lower_bounded!(isize, usize);
4248 #[cfg(target_pointer_width = "16")]
4249 mod ptr_try_from_impls {
4250 use super::TryFromIntError;
4251 use convert::TryFrom;
4253 try_from_upper_bounded!(usize, u8);
4254 try_from_unbounded!(usize, u16, u32, u64, u128);
4255 try_from_upper_bounded!(usize, i8, i16);
4256 try_from_unbounded!(usize, i32, i64, i128);
4258 try_from_both_bounded!(isize, u8);
4259 try_from_lower_bounded!(isize, u16, u32, u64, u128);
4260 try_from_both_bounded!(isize, i8);
4261 try_from_unbounded!(isize, i16, i32, i64, i128);
4263 rev!(try_from_unbounded, usize, u16);
4264 rev!(try_from_upper_bounded, usize, u32, u64, u128);
4265 rev!(try_from_lower_bounded, usize, i8, i16);
4266 rev!(try_from_both_bounded, usize, i32, i64, i128);
4268 rev!(try_from_unbounded, isize, u8);
4269 rev!(try_from_upper_bounded, isize, u16, u32, u64, u128);
4270 rev!(try_from_unbounded, isize, i16);
4271 rev!(try_from_both_bounded, isize, i32, i64, i128);
4274 #[cfg(target_pointer_width = "32")]
4275 mod ptr_try_from_impls {
4276 use super::TryFromIntError;
4277 use convert::TryFrom;
4279 try_from_upper_bounded!(usize, u8, u16);
4280 try_from_unbounded!(usize, u32, u64, u128);
4281 try_from_upper_bounded!(usize, i8, i16, i32);
4282 try_from_unbounded!(usize, i64, i128);
4284 try_from_both_bounded!(isize, u8, u16);
4285 try_from_lower_bounded!(isize, u32, u64, u128);
4286 try_from_both_bounded!(isize, i8, i16);
4287 try_from_unbounded!(isize, i32, i64, i128);
4289 rev!(try_from_unbounded, usize, u16, u32);
4290 rev!(try_from_upper_bounded, usize, u64, u128);
4291 rev!(try_from_lower_bounded, usize, i8, i16, i32);
4292 rev!(try_from_both_bounded, usize, i64, i128);
4294 rev!(try_from_unbounded, isize, u8, u16);
4295 rev!(try_from_upper_bounded, isize, u32, u64, u128);
4296 rev!(try_from_unbounded, isize, i16, i32);
4297 rev!(try_from_both_bounded, isize, i64, i128);
4300 #[cfg(target_pointer_width = "64")]
4301 mod ptr_try_from_impls {
4302 use super::TryFromIntError;
4303 use convert::TryFrom;
4305 try_from_upper_bounded!(usize, u8, u16, u32);
4306 try_from_unbounded!(usize, u64, u128);
4307 try_from_upper_bounded!(usize, i8, i16, i32, i64);
4308 try_from_unbounded!(usize, i128);
4310 try_from_both_bounded!(isize, u8, u16, u32);
4311 try_from_lower_bounded!(isize, u64, u128);
4312 try_from_both_bounded!(isize, i8, i16, i32);
4313 try_from_unbounded!(isize, i64, i128);
4315 rev!(try_from_unbounded, usize, u16, u32, u64);
4316 rev!(try_from_upper_bounded, usize, u128);
4317 rev!(try_from_lower_bounded, usize, i8, i16, i32, i64);
4318 rev!(try_from_both_bounded, usize, i128);
4320 rev!(try_from_unbounded, isize, u8, u16, u32);
4321 rev!(try_from_upper_bounded, isize, u64, u128);
4322 rev!(try_from_unbounded, isize, i16, i32, i64);
4323 rev!(try_from_both_bounded, isize, i128);
4327 trait FromStrRadixHelper: PartialOrd + Copy {
4328 fn min_value() -> Self;
4329 fn max_value() -> Self;
4330 fn from_u32(u: u32) -> Self;
4331 fn checked_mul(&self, other: u32) -> Option<Self>;
4332 fn checked_sub(&self, other: u32) -> Option<Self>;
4333 fn checked_add(&self, other: u32) -> Option<Self>;
4337 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
4339 fn min_value() -> Self { Self::min_value() }
4341 fn max_value() -> Self { Self::max_value() }
4343 fn from_u32(u: u32) -> Self { u as Self }
4345 fn checked_mul(&self, other: u32) -> Option<Self> {
4346 Self::checked_mul(*self, other as Self)
4349 fn checked_sub(&self, other: u32) -> Option<Self> {
4350 Self::checked_sub(*self, other as Self)
4353 fn checked_add(&self, other: u32) -> Option<Self> {
4354 Self::checked_add(*self, other as Self)
4358 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
4360 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
4361 use self::IntErrorKind::*;
4362 use self::ParseIntError as PIE;
4364 assert!(radix >= 2 && radix <= 36,
4365 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
4369 return Err(PIE { kind: Empty });
4372 let is_signed_ty = T::from_u32(0) > T::min_value();
4374 // all valid digits are ascii, so we will just iterate over the utf8 bytes
4375 // and cast them to chars. .to_digit() will safely return None for anything
4376 // other than a valid ascii digit for the given radix, including the first-byte
4377 // of multi-byte sequences
4378 let src = src.as_bytes();
4380 let (is_positive, digits) = match src[0] {
4381 b'+' => (true, &src[1..]),
4382 b'-' if is_signed_ty => (false, &src[1..]),
4386 if digits.is_empty() {
4387 return Err(PIE { kind: Empty });
4390 let mut result = T::from_u32(0);
4392 // The number is positive
4394 let x = match (c as char).to_digit(radix) {
4396 None => return Err(PIE { kind: InvalidDigit }),
4398 result = match result.checked_mul(radix) {
4399 Some(result) => result,
4400 None => return Err(PIE { kind: Overflow }),
4402 result = match result.checked_add(x) {
4403 Some(result) => result,
4404 None => return Err(PIE { kind: Overflow }),
4408 // The number is negative
4410 let x = match (c as char).to_digit(radix) {
4412 None => return Err(PIE { kind: InvalidDigit }),
4414 result = match result.checked_mul(radix) {
4415 Some(result) => result,
4416 None => return Err(PIE { kind: Underflow }),
4418 result = match result.checked_sub(x) {
4419 Some(result) => result,
4420 None => return Err(PIE { kind: Underflow }),
4427 /// An error which can be returned when parsing an integer.
4429 /// This error is used as the error type for the `from_str_radix()` functions
4430 /// on the primitive integer types, such as [`i8::from_str_radix`].
4432 /// # Potential causes
4434 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
4435 /// in the string e.g. when it is obtained from the standard input.
4436 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
4438 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
4439 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
4440 #[derive(Debug, Clone, PartialEq, Eq)]
4441 #[stable(feature = "rust1", since = "1.0.0")]
4442 pub struct ParseIntError {
4446 #[derive(Debug, Clone, PartialEq, Eq)]
4454 impl ParseIntError {
4455 #[unstable(feature = "int_error_internals",
4456 reason = "available through Error trait and this method should \
4457 not be exposed publicly",
4460 pub fn __description(&self) -> &str {
4462 IntErrorKind::Empty => "cannot parse integer from empty string",
4463 IntErrorKind::InvalidDigit => "invalid digit found in string",
4464 IntErrorKind::Overflow => "number too large to fit in target type",
4465 IntErrorKind::Underflow => "number too small to fit in target type",
4470 #[stable(feature = "rust1", since = "1.0.0")]
4471 impl fmt::Display for ParseIntError {
4472 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4473 self.__description().fmt(f)
4477 #[stable(feature = "rust1", since = "1.0.0")]
4478 pub use num::dec2flt::ParseFloatError;
4480 // Conversion traits for primitive integer and float types
4481 // Conversions T -> T are covered by a blanket impl and therefore excluded
4482 // Some conversions from and to usize/isize are not implemented due to portability concerns
4483 macro_rules! impl_from {
4484 ($Small: ty, $Large: ty, #[$attr:meta]) => {
4486 impl From<$Small> for $Large {
4488 fn from(small: $Small) -> $Large {
4495 // Unsigned -> Unsigned
4496 impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4497 impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4498 impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4499 impl_from! { u8, u128, #[unstable(feature = "i128", issue = "35118")] }
4500 impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4501 impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4502 impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4503 impl_from! { u16, u128, #[unstable(feature = "i128", issue = "35118")] }
4504 impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4505 impl_from! { u32, u128, #[unstable(feature = "i128", issue = "35118")] }
4506 impl_from! { u64, u128, #[unstable(feature = "i128", issue = "35118")] }
4509 impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4510 impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4511 impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4512 impl_from! { i8, i128, #[unstable(feature = "i128", issue = "35118")] }
4513 impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4514 impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4515 impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4516 impl_from! { i16, i128, #[unstable(feature = "i128", issue = "35118")] }
4517 impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4518 impl_from! { i32, i128, #[unstable(feature = "i128", issue = "35118")] }
4519 impl_from! { i64, i128, #[unstable(feature = "i128", issue = "35118")] }
4521 // Unsigned -> Signed
4522 impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4523 impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4524 impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4525 impl_from! { u8, i128, #[unstable(feature = "i128", issue = "35118")] }
4526 impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4527 impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4528 impl_from! { u16, i128, #[unstable(feature = "i128", issue = "35118")] }
4529 impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4530 impl_from! { u32, i128, #[unstable(feature = "i128", issue = "35118")] }
4531 impl_from! { u64, i128, #[unstable(feature = "i128", issue = "35118")] }
4533 // Note: integers can only be represented with full precision in a float if
4534 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
4535 // Lossy float conversions are not implemented at this time.
4538 impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4539 impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4540 impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4541 impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4542 impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4544 // Unsigned -> Float
4545 impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4546 impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4547 impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4548 impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4549 impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4552 impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4554 static ASCII_LOWERCASE_MAP: [u8; 256] = [
4555 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4556 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4557 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4558 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4559 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4560 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4561 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4562 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4565 b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4566 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4567 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4570 b'[', b'\\', b']', b'^', b'_',
4571 b'`', b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4572 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4573 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4574 b'x', b'y', b'z', b'{', b'|', b'}', b'~', 0x7f,
4575 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4576 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4577 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4578 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4579 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4580 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4581 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4582 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4583 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4584 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4585 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4586 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4587 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4588 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4589 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4590 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4593 static ASCII_UPPERCASE_MAP: [u8; 256] = [
4594 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4595 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4596 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4597 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4598 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4599 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4600 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4601 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4602 b'@', b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4603 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4604 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4605 b'X', b'Y', b'Z', b'[', b'\\', b']', b'^', b'_',
4608 b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4609 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4610 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4613 b'{', b'|', b'}', b'~', 0x7f,
4614 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4615 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4616 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4617 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4618 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4619 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4620 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4621 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4622 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4623 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4624 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4625 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4626 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4627 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4628 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4629 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4632 enum AsciiCharacterClass {
4634 Cw, // control whitespace
4638 Lx, // lowercase hex digit
4640 Ux, // uppercase hex digit
4643 use self::AsciiCharacterClass::*;
4645 static ASCII_CHARACTER_CLASS: [AsciiCharacterClass; 128] = [
4646 // _0 _1 _2 _3 _4 _5 _6 _7 _8 _9 _a _b _c _d _e _f
4647 C, C, C, C, C, C, C, C, C, Cw,Cw,C, Cw,Cw,C, C, // 0_
4648 C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, // 1_
4649 W, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, // 2_
4650 D, D, D, D, D, D, D, D, D, D, P, P, P, P, P, P, // 3_
4651 P, Ux,Ux,Ux,Ux,Ux,Ux,U, U, U, U, U, U, U, U, U, // 4_
4652 U, U, U, U, U, U, U, U, U, U, U, P, P, P, P, P, // 5_
4653 P, Lx,Lx,Lx,Lx,Lx,Lx,L, L, L, L, L, L, L, L, L, // 6_
4654 L, L, L, L, L, L, L, L, L, L, L, P, P, P, P, C, // 7_