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")]
15 use convert::{Infallible, TryFrom};
21 /// Provides intentionally-wrapped arithmetic on `T`.
23 /// Operations like `+` on `u32` values is intended to never overflow,
24 /// and in some debug configurations overflow is detected and results
25 /// in a panic. While most arithmetic falls into this category, some
26 /// code explicitly expects and relies upon modular arithmetic (e.g.,
29 /// Wrapping arithmetic can be achieved either through methods like
30 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
31 /// all standard arithmetic operations on the underlying value are
32 /// intended to have wrapping semantics.
37 /// use std::num::Wrapping;
39 /// let zero = Wrapping(0u32);
40 /// let one = Wrapping(1u32);
42 /// assert_eq!(std::u32::MAX, (zero - one).0);
44 #[stable(feature = "rust1", since = "1.0.0")]
45 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
46 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")]
49 #[stable(feature = "rust1", since = "1.0.0")]
50 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
51 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
56 #[stable(feature = "wrapping_display", since = "1.10.0")]
57 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
58 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
63 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
64 impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
65 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
70 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
71 impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
72 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
77 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
78 impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
79 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
84 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
85 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
86 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
93 // All these modules are technically private and only exposed for coretests:
99 macro_rules! doc_comment {
100 ($x:expr, $($tt:tt)*) => {
106 // `Int` + `SignedInt` implemented for signed integers
107 macro_rules! int_impl {
108 ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $Min:expr, $Max:expr, $Feature:expr,
109 $EndFeature:expr) => {
111 concat!("Returns the smallest value that can be represented by this integer type.
118 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), ", stringify!($Min), ");",
121 #[stable(feature = "rust1", since = "1.0.0")]
123 pub const fn min_value() -> Self {
124 !0 ^ ((!0 as $UnsignedT) >> 1) as Self
129 concat!("Returns the largest value that can be represented by this integer type.
136 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ", stringify!($Max), ");",
139 #[stable(feature = "rust1", since = "1.0.0")]
141 pub const fn max_value() -> Self {
147 concat!("Converts a string slice in a given base to an integer.
149 The string is expected to be an optional `+` or `-` sign followed by digits.
150 Leading and trailing whitespace represent an error. Digits are a subset of these characters,
151 depending on `radix`:
159 This function panics if `radix` is not in the range from 2 to 36.
166 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
169 #[stable(feature = "rust1", since = "1.0.0")]
170 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
171 from_str_radix(src, radix)
176 concat!("Returns the number of ones in the binary representation of `self`.
183 ", $Feature, "let n = 0b100_0000", stringify!($SelfT), ";
185 assert_eq!(n.count_ones(), 1);",
189 #[stable(feature = "rust1", since = "1.0.0")]
191 pub fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
195 concat!("Returns the number of zeros in the binary representation of `self`.
202 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 1);", $EndFeature, "
204 #[stable(feature = "rust1", since = "1.0.0")]
206 pub fn count_zeros(self) -> u32 {
212 concat!("Returns the number of leading zeros in the binary representation of `self`.
219 ", $Feature, "let n = -1", stringify!($SelfT), ";
221 assert_eq!(n.leading_zeros(), 0);",
224 #[stable(feature = "rust1", since = "1.0.0")]
226 pub fn leading_zeros(self) -> u32 {
227 (self as $UnsignedT).leading_zeros()
232 concat!("Returns the number of trailing zeros in the binary representation of `self`.
239 ", $Feature, "let n = -4", stringify!($SelfT), ";
241 assert_eq!(n.trailing_zeros(), 2);",
244 #[stable(feature = "rust1", since = "1.0.0")]
246 pub fn trailing_zeros(self) -> u32 {
247 (self as $UnsignedT).trailing_zeros()
251 /// Shifts the bits to the left by a specified amount, `n`,
252 /// wrapping the truncated bits to the end of the resulting integer.
254 /// Please note this isn't the same operation as `<<`!
258 /// Please note that this example is shared between integer types.
259 /// Which explains why `i64` is used here.
264 /// let n = 0x0123456789ABCDEFi64;
265 /// let m = -0x76543210FEDCBA99i64;
267 /// assert_eq!(n.rotate_left(32), m);
269 #[stable(feature = "rust1", since = "1.0.0")]
271 pub fn rotate_left(self, n: u32) -> Self {
272 (self as $UnsignedT).rotate_left(n) as Self
275 /// Shifts the bits to the right by a specified amount, `n`,
276 /// wrapping the truncated bits to the beginning of the resulting
279 /// Please note this isn't the same operation as `>>`!
283 /// Please note that this example is shared between integer types.
284 /// Which explains why `i64` is used here.
289 /// let n = 0x0123456789ABCDEFi64;
290 /// let m = -0xFEDCBA987654322i64;
292 /// assert_eq!(n.rotate_right(4), m);
294 #[stable(feature = "rust1", since = "1.0.0")]
296 pub fn rotate_right(self, n: u32) -> Self {
297 (self as $UnsignedT).rotate_right(n) as Self
300 /// Reverses the byte order of the integer.
304 /// Please note that this example is shared between integer types.
305 /// Which explains why `i16` is used here.
310 /// let n: i16 = 0b0000000_01010101;
311 /// assert_eq!(n, 85);
313 /// let m = n.swap_bytes();
315 /// assert_eq!(m, 0b01010101_00000000);
316 /// assert_eq!(m, 21760);
318 #[stable(feature = "rust1", since = "1.0.0")]
320 pub fn swap_bytes(self) -> Self {
321 (self as $UnsignedT).swap_bytes() as Self
324 /// Reverses the bit pattern of the integer.
328 /// Please note that this example is shared between integer types.
329 /// Which explains why `i16` is used here.
334 /// #![feature(reverse_bits)]
336 /// let n: i16 = 0b0000000_01010101;
337 /// assert_eq!(n, 85);
339 /// let m = n.reverse_bits();
341 /// assert_eq!(m as u16, 0b10101010_00000000);
342 /// assert_eq!(m, -22016);
344 #[unstable(feature = "reverse_bits", issue = "48763")]
347 pub fn reverse_bits(self) -> Self {
348 (self as $UnsignedT).reverse_bits() as Self
352 concat!("Converts an integer from big endian to the target's endianness.
354 On big endian this is a no-op. On little endian the bytes are swapped.
361 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
363 if cfg!(target_endian = \"big\") {
364 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
366 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
370 #[stable(feature = "rust1", since = "1.0.0")]
372 pub fn from_be(x: Self) -> Self {
373 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
378 concat!("Converts an integer from little endian to the target's endianness.
380 On little endian this is a no-op. On big endian the bytes are swapped.
387 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
389 if cfg!(target_endian = \"little\") {
390 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
392 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
396 #[stable(feature = "rust1", since = "1.0.0")]
398 pub fn from_le(x: Self) -> Self {
399 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
404 concat!("Converts `self` to big endian from the target's endianness.
406 On big endian this is a no-op. On little endian the bytes are swapped.
413 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
415 if cfg!(target_endian = \"big\") {
416 assert_eq!(n.to_be(), n)
418 assert_eq!(n.to_be(), n.swap_bytes())
422 #[stable(feature = "rust1", since = "1.0.0")]
424 pub fn to_be(self) -> Self { // or not to be?
425 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
430 concat!("Converts `self` to little endian from the target's endianness.
432 On little endian this is a no-op. On big endian the bytes are swapped.
439 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
441 if cfg!(target_endian = \"little\") {
442 assert_eq!(n.to_le(), n)
444 assert_eq!(n.to_le(), n.swap_bytes())
448 #[stable(feature = "rust1", since = "1.0.0")]
450 pub fn to_le(self) -> Self {
451 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
456 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
457 if overflow occurred.
464 ", $Feature, "assert_eq!((", stringify!($SelfT),
465 "::max_value() - 2).checked_add(1), Some(", stringify!($SelfT), "::max_value() - 1));
466 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);",
469 #[stable(feature = "rust1", since = "1.0.0")]
471 pub fn checked_add(self, rhs: Self) -> Option<Self> {
472 let (a, b) = self.overflowing_add(rhs);
473 if b {None} else {Some(a)}
478 concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
486 ", $Feature, "assert_eq!((", stringify!($SelfT),
487 "::min_value() + 2).checked_sub(1), Some(", stringify!($SelfT), "::min_value() + 1));
488 assert_eq!((", stringify!($SelfT), "::min_value() + 2).checked_sub(3), None);",
491 #[stable(feature = "rust1", since = "1.0.0")]
493 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
494 let (a, b) = self.overflowing_sub(rhs);
495 if b {None} else {Some(a)}
500 concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
508 ", $Feature, "assert_eq!(", stringify!($SelfT),
509 "::max_value().checked_mul(1), Some(", stringify!($SelfT), "::max_value()));
510 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);",
513 #[stable(feature = "rust1", since = "1.0.0")]
515 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
516 let (a, b) = self.overflowing_mul(rhs);
517 if b {None} else {Some(a)}
522 concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
523 or the division results in overflow.
530 ", $Feature, "assert_eq!((", stringify!($SelfT),
531 "::min_value() + 1).checked_div(-1), Some(", stringify!($Max), "));
532 assert_eq!(", stringify!($SelfT), "::min_value().checked_div(-1), None);
533 assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
536 #[stable(feature = "rust1", since = "1.0.0")]
538 pub fn checked_div(self, rhs: Self) -> Option<Self> {
539 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
542 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
548 concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
549 `rhs == 0` or the division results in overflow.
556 ", $Feature, "use std::", stringify!($SelfT), ";
558 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
559 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
560 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
563 #[stable(feature = "wrapping", since = "1.7.0")]
565 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
566 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
569 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
575 concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
582 ", $Feature, "use std::", stringify!($SelfT), ";
584 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
585 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
588 #[stable(feature = "wrapping", since = "1.7.0")]
590 pub fn checked_neg(self) -> Option<Self> {
591 let (a, b) = self.overflowing_neg();
592 if b {None} else {Some(a)}
597 concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
598 than or equal to the number of bits in `self`.
605 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
606 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
609 #[stable(feature = "wrapping", since = "1.7.0")]
611 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
612 let (a, b) = self.overflowing_shl(rhs);
613 if b {None} else {Some(a)}
618 concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
619 larger than or equal to the number of bits in `self`.
626 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
627 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
630 #[stable(feature = "wrapping", since = "1.7.0")]
632 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
633 let (a, b) = self.overflowing_shr(rhs);
634 if b {None} else {Some(a)}
639 concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
647 ", $Feature, "use std::", stringify!($SelfT), ";
649 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
650 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
653 #[stable(feature = "no_panic_abs", since = "1.13.0")]
655 pub fn checked_abs(self) -> Option<Self> {
656 if self.is_negative() {
665 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
673 #![feature(no_panic_pow)]
674 ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
675 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);",
679 #[unstable(feature = "no_panic_pow", issue = "48320")]
681 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
683 let mut acc: Self = 1;
687 acc = acc.checked_mul(base)?;
690 base = base.checked_mul(base)?;
693 // Deal with the final bit of the exponent separately, since
694 // squaring the base afterwards is not necessary and may cause a
695 // needless overflow.
697 acc = acc.checked_mul(base)?;
705 concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
706 bounds instead of overflowing.
713 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
714 assert_eq!(", stringify!($SelfT), "::max_value().saturating_add(100), ", stringify!($SelfT),
718 #[stable(feature = "rust1", since = "1.0.0")]
720 pub fn saturating_add(self, rhs: Self) -> Self {
721 match self.checked_add(rhs) {
723 None if rhs >= 0 => Self::max_value(),
724 None => Self::min_value(),
730 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
731 numeric bounds instead of overflowing.
738 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
739 assert_eq!(", stringify!($SelfT), "::min_value().saturating_sub(100), ", stringify!($SelfT),
743 #[stable(feature = "rust1", since = "1.0.0")]
745 pub fn saturating_sub(self, rhs: Self) -> Self {
746 match self.checked_sub(rhs) {
748 None if rhs >= 0 => Self::min_value(),
749 None => Self::max_value(),
755 concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
756 numeric bounds instead of overflowing.
763 ", $Feature, "use std::", stringify!($SelfT), ";
765 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
766 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
767 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
770 #[stable(feature = "wrapping", since = "1.7.0")]
772 pub fn saturating_mul(self, rhs: Self) -> Self {
773 self.checked_mul(rhs).unwrap_or_else(|| {
774 if (self < 0 && rhs < 0) || (self > 0 && rhs > 0) {
784 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
785 saturating at the numeric bounds instead of overflowing.
792 #![feature(no_panic_pow)]
793 ", $Feature, "use std::", stringify!($SelfT), ";
795 assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
796 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
797 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
800 #[unstable(feature = "no_panic_pow", issue = "48320")]
802 pub fn saturating_pow(self, exp: u32) -> Self {
803 match self.checked_pow(exp) {
805 None if self < 0 && exp % 2 == 1 => Self::min_value(),
806 None => Self::max_value(),
812 concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
813 boundary of the type.
820 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
821 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_add(2), ", stringify!($SelfT),
822 "::min_value() + 1);",
825 #[stable(feature = "rust1", since = "1.0.0")]
827 pub fn wrapping_add(self, rhs: Self) -> Self {
829 intrinsics::overflowing_add(self, rhs)
835 concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
836 boundary of the type.
843 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
844 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::max_value()), ",
845 stringify!($SelfT), "::max_value());",
848 #[stable(feature = "rust1", since = "1.0.0")]
850 pub fn wrapping_sub(self, rhs: Self) -> Self {
852 intrinsics::overflowing_sub(self, rhs)
858 concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
859 the boundary of the type.
866 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
867 assert_eq!(11i8.wrapping_mul(12), -124);",
870 #[stable(feature = "rust1", since = "1.0.0")]
872 pub fn wrapping_mul(self, rhs: Self) -> Self {
874 intrinsics::overflowing_mul(self, rhs)
880 concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
881 boundary of the type.
883 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
884 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
885 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
889 This function will panic if `rhs` is 0.
896 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
897 assert_eq!((-128i8).wrapping_div(-1), -128);",
900 #[stable(feature = "num_wrapping", since = "1.2.0")]
902 pub fn wrapping_div(self, rhs: Self) -> Self {
903 self.overflowing_div(rhs).0
908 concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
909 boundary of the type.
911 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
912 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
913 this function returns `0`.
917 This function will panic if `rhs` is 0.
924 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
925 assert_eq!((-128i8).wrapping_rem(-1), 0);",
928 #[stable(feature = "num_wrapping", since = "1.2.0")]
930 pub fn wrapping_rem(self, rhs: Self) -> Self {
931 self.overflowing_rem(rhs).0
936 concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
939 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
940 is the negative minimal value for the type); this is a positive value that is too large to represent
941 in the type. In such a case, this function returns `MIN` itself.
948 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
949 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_neg(), ", stringify!($SelfT),
953 #[stable(feature = "num_wrapping", since = "1.2.0")]
955 pub fn wrapping_neg(self) -> Self {
956 self.overflowing_neg().0
961 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
962 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
964 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
965 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
966 The primitive integer types all implement a `rotate_left` function, which may be what you want
974 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
975 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
978 #[stable(feature = "num_wrapping", since = "1.2.0")]
980 pub fn wrapping_shl(self, rhs: u32) -> Self {
982 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
988 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
989 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
991 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
992 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
993 end. The primitive integer types all implement a `rotate_right` function, which may be what you want
1001 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
1002 assert_eq!((-128i16).wrapping_shr(64), -128);",
1005 #[stable(feature = "num_wrapping", since = "1.2.0")]
1007 pub fn wrapping_shr(self, rhs: u32) -> Self {
1009 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1015 concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1016 the boundary of the type.
1018 The only case where such wrapping can occur is when one takes the absolute value of the negative
1019 minimal value for the type this is a positive value that is too large to represent in the type. In
1020 such a case, this function returns `MIN` itself.
1027 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
1028 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
1029 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_abs(), ", stringify!($SelfT),
1031 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1034 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1036 pub fn wrapping_abs(self) -> Self {
1037 if self.is_negative() {
1046 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1047 wrapping around at the boundary of the type.
1054 #![feature(no_panic_pow)]
1055 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);
1056 assert_eq!(3i8.wrapping_pow(5), -13);
1057 assert_eq!(3i8.wrapping_pow(6), -39);",
1060 #[unstable(feature = "no_panic_pow", issue = "48320")]
1062 pub fn wrapping_pow(self, mut exp: u32) -> Self {
1063 let mut base = self;
1064 let mut acc: Self = 1;
1068 acc = acc.wrapping_mul(base);
1071 base = base.wrapping_mul(base);
1074 // Deal with the final bit of the exponent separately, since
1075 // squaring the base afterwards is not necessary and may cause a
1076 // needless overflow.
1078 acc = acc.wrapping_mul(base);
1086 concat!("Calculates `self` + `rhs`
1088 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1089 occur. If an overflow would have occurred then the wrapped value is returned.
1096 ", $Feature, "use std::", stringify!($SelfT), ";
1098 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1099 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
1100 "::MIN, true));", $EndFeature, "
1103 #[stable(feature = "wrapping", since = "1.7.0")]
1104 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1105 let (a, b) = unsafe {
1106 intrinsics::add_with_overflow(self as $ActualT,
1114 concat!("Calculates `self` - `rhs`
1116 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1117 would occur. If an overflow would have occurred then the wrapped value is returned.
1124 ", $Feature, "use std::", stringify!($SelfT), ";
1126 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
1127 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
1128 "::MAX, true));", $EndFeature, "
1131 #[stable(feature = "wrapping", since = "1.7.0")]
1132 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1133 let (a, b) = unsafe {
1134 intrinsics::sub_with_overflow(self as $ActualT,
1142 concat!("Calculates the multiplication of `self` and `rhs`.
1144 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1145 would occur. If an overflow would have occurred then the wrapped value is returned.
1152 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1153 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1157 #[stable(feature = "wrapping", since = "1.7.0")]
1158 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1159 let (a, b) = unsafe {
1160 intrinsics::mul_with_overflow(self as $ActualT,
1168 concat!("Calculates the divisor when `self` is divided by `rhs`.
1170 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1171 occur. If an overflow would occur then self is returned.
1175 This function will panic if `rhs` is 0.
1182 ", $Feature, "use std::", stringify!($SelfT), ";
1184 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1185 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1190 #[stable(feature = "wrapping", since = "1.7.0")]
1191 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1192 if self == Self::min_value() && rhs == -1 {
1201 concat!("Calculates the remainder when `self` is divided by `rhs`.
1203 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1204 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1208 This function will panic if `rhs` is 0.
1215 ", $Feature, "use std::", stringify!($SelfT), ";
1217 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1218 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1222 #[stable(feature = "wrapping", since = "1.7.0")]
1223 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1224 if self == Self::min_value() && rhs == -1 {
1233 concat!("Negates self, overflowing if this is equal to the minimum value.
1235 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1236 happened. If `self` is the minimum value (e.g. `i32::MIN` for values of type `i32`), then the
1237 minimum value will be returned again and `true` will be returned for an overflow happening.
1244 ", $Feature, "use std::", stringify!($SelfT), ";
1246 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1247 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1248 "::MIN, true));", $EndFeature, "
1251 #[stable(feature = "wrapping", since = "1.7.0")]
1252 pub fn overflowing_neg(self) -> (Self, bool) {
1253 if self == Self::min_value() {
1254 (Self::min_value(), true)
1262 concat!("Shifts self left by `rhs` bits.
1264 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1265 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1266 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1273 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1274 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1278 #[stable(feature = "wrapping", since = "1.7.0")]
1279 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1280 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1285 concat!("Shifts self right by `rhs` bits.
1287 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1288 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1289 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1296 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1297 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1301 #[stable(feature = "wrapping", since = "1.7.0")]
1302 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1303 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1308 concat!("Computes the absolute value of `self`.
1310 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1311 happened. If self is the minimum value (e.g. ", stringify!($SelfT), "::MIN for values of type
1312 ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1313 for an overflow happening.
1320 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1321 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1322 assert_eq!((", stringify!($SelfT), "::min_value()).overflowing_abs(), (", stringify!($SelfT),
1323 "::min_value(), true));",
1326 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1328 pub fn overflowing_abs(self) -> (Self, bool) {
1329 if self.is_negative() {
1330 self.overflowing_neg()
1338 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1340 Returns a tuple of the exponentiation along with a bool indicating
1341 whether an overflow happened.
1348 #![feature(no_panic_pow)]
1349 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));
1350 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
1353 #[unstable(feature = "no_panic_pow", issue = "48320")]
1355 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1356 let mut base = self;
1357 let mut acc: Self = 1;
1358 let mut overflown = false;
1359 // Scratch space for storing results of overflowing_mul.
1364 r = acc.overflowing_mul(base);
1369 r = base.overflowing_mul(base);
1374 // Deal with the final bit of the exponent separately, since
1375 // squaring the base afterwards is not necessary and may cause a
1376 // needless overflow.
1378 r = acc.overflowing_mul(base);
1388 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1395 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
1397 assert_eq!(x.pow(5), 32);",
1400 #[stable(feature = "rust1", since = "1.0.0")]
1402 #[rustc_inherit_overflow_checks]
1403 pub fn pow(self, mut exp: u32) -> Self {
1404 let mut base = self;
1415 // Deal with the final bit of the exponent separately, since
1416 // squaring the base afterwards is not necessary and may cause a
1417 // needless overflow.
1427 concat!("Computes the absolute value of `self`.
1431 The absolute value of `", stringify!($SelfT), "::min_value()` cannot be represented as an
1432 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
1433 code in debug mode will trigger a panic on this case and optimized code will return `",
1434 stringify!($SelfT), "::min_value()` without a panic.
1441 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
1442 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
1445 #[stable(feature = "rust1", since = "1.0.0")]
1447 #[rustc_inherit_overflow_checks]
1448 pub fn abs(self) -> Self {
1449 if self.is_negative() {
1450 // Note that the #[inline] above means that the overflow
1451 // semantics of this negation depend on the crate we're being
1461 concat!("Returns a number representing sign of `self`.
1463 - `0` if the number is zero
1464 - `1` if the number is positive
1465 - `-1` if the number is negative
1472 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
1473 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
1474 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
1477 #[stable(feature = "rust1", since = "1.0.0")]
1479 pub fn signum(self) -> Self {
1489 concat!("Returns `true` if `self` is positive and `false` if the number is zero or
1497 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
1498 assert!(!(-10", stringify!($SelfT), ").is_positive());",
1501 #[stable(feature = "rust1", since = "1.0.0")]
1503 pub fn is_positive(self) -> bool { self > 0 }
1507 concat!("Returns `true` if `self` is negative and `false` if the number is zero or
1515 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
1516 assert!(!10", stringify!($SelfT), ".is_negative());",
1519 #[stable(feature = "rust1", since = "1.0.0")]
1521 pub fn is_negative(self) -> bool { self < 0 }
1528 int_impl! { i8, i8, u8, 8, -128, 127, "", "" }
1533 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "" }
1538 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "" }
1543 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "" }
1548 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
1549 170141183460469231731687303715884105727, "#![feature(i128_type)]
1556 #[cfg(target_pointer_width = "16")]
1559 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "" }
1562 #[cfg(target_pointer_width = "32")]
1565 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "" }
1568 #[cfg(target_pointer_width = "64")]
1571 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "" }
1574 // `Int` + `UnsignedInt` implemented for unsigned integers
1575 macro_rules! uint_impl {
1576 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr) => {
1578 concat!("Returns the smallest value that can be represented by this integer type.
1585 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), 0);", $EndFeature, "
1587 #[stable(feature = "rust1", since = "1.0.0")]
1589 pub const fn min_value() -> Self { 0 }
1593 concat!("Returns the largest value that can be represented by this integer type.
1600 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ",
1601 stringify!($MaxV), ");", $EndFeature, "
1603 #[stable(feature = "rust1", since = "1.0.0")]
1605 pub const fn max_value() -> Self { !0 }
1609 concat!("Converts a string slice in a given base to an integer.
1611 The string is expected to be an optional `+` sign
1613 Leading and trailing whitespace represent an error.
1614 Digits are a subset of these characters, depending on `radix`:
1622 This function panics if `radix` is not in the range from 2 to 36.
1629 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
1632 #[stable(feature = "rust1", since = "1.0.0")]
1633 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
1634 from_str_radix(src, radix)
1639 concat!("Returns the number of ones in the binary representation of `self`.
1646 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
1648 assert_eq!(n.count_ones(), 3);", $EndFeature, "
1650 #[stable(feature = "rust1", since = "1.0.0")]
1652 pub fn count_ones(self) -> u32 {
1653 unsafe { intrinsics::ctpop(self as $ActualT) as u32 }
1658 concat!("Returns the number of zeros in the binary representation of `self`.
1665 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 0);", $EndFeature, "
1667 #[stable(feature = "rust1", since = "1.0.0")]
1669 pub fn count_zeros(self) -> u32 {
1670 (!self).count_ones()
1675 concat!("Returns the number of leading zeros in the binary representation of `self`.
1682 ", $Feature, "let n = ", stringify!($SelfT), "::max_value() >> 2;
1684 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
1686 #[stable(feature = "rust1", since = "1.0.0")]
1688 pub fn leading_zeros(self) -> u32 {
1689 unsafe { intrinsics::ctlz(self as $ActualT) as u32 }
1694 concat!("Returns the number of trailing zeros in the binary representation
1702 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
1704 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
1706 #[stable(feature = "rust1", since = "1.0.0")]
1708 pub fn trailing_zeros(self) -> u32 {
1709 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
1710 // emits two conditional moves on x86_64. By promoting the value to
1711 // u16 and setting bit 8, we get better code without any conditional
1713 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
1714 // pending, remove this workaround once LLVM generates better code
1718 intrinsics::cttz(self as u16 | 0x100) as u32
1720 intrinsics::cttz(self) as u32
1726 /// Shifts the bits to the left by a specified amount, `n`,
1727 /// wrapping the truncated bits to the end of the resulting integer.
1729 /// Please note this isn't the same operation as `<<`!
1735 /// Please note that this example is shared between integer types.
1736 /// Which explains why `u64` is used here.
1739 /// let n = 0x0123456789ABCDEFu64;
1740 /// let m = 0x3456789ABCDEF012u64;
1742 /// assert_eq!(n.rotate_left(12), m);
1744 #[stable(feature = "rust1", since = "1.0.0")]
1746 pub fn rotate_left(self, n: u32) -> Self {
1747 // Protect against undefined behaviour for over-long bit shifts
1749 (self << n) | (self >> (($BITS - n) % $BITS))
1752 /// Shifts the bits to the right by a specified amount, `n`,
1753 /// wrapping the truncated bits to the beginning of the resulting
1756 /// Please note this isn't the same operation as `>>`!
1762 /// Please note that this example is shared between integer types.
1763 /// Which explains why `u64` is used here.
1766 /// let n = 0x0123456789ABCDEFu64;
1767 /// let m = 0xDEF0123456789ABCu64;
1769 /// assert_eq!(n.rotate_right(12), m);
1771 #[stable(feature = "rust1", since = "1.0.0")]
1773 pub fn rotate_right(self, n: u32) -> Self {
1774 // Protect against undefined behaviour for over-long bit shifts
1776 (self >> n) | (self << (($BITS - n) % $BITS))
1779 /// Reverses the byte order of the integer.
1785 /// Please note that this example is shared between integer types.
1786 /// Which explains why `u16` is used here.
1789 /// let n: u16 = 0b0000000_01010101;
1790 /// assert_eq!(n, 85);
1792 /// let m = n.swap_bytes();
1794 /// assert_eq!(m, 0b01010101_00000000);
1795 /// assert_eq!(m, 21760);
1797 #[stable(feature = "rust1", since = "1.0.0")]
1799 pub fn swap_bytes(self) -> Self {
1800 unsafe { intrinsics::bswap(self as $ActualT) as Self }
1803 /// Reverses the bit pattern of the integer.
1809 /// Please note that this example is shared between integer types.
1810 /// Which explains why `u16` is used here.
1813 /// #![feature(reverse_bits)]
1815 /// let n: u16 = 0b0000000_01010101;
1816 /// assert_eq!(n, 85);
1818 /// let m = n.reverse_bits();
1820 /// assert_eq!(m, 0b10101010_00000000);
1821 /// assert_eq!(m, 43520);
1823 #[unstable(feature = "reverse_bits", issue = "48763")]
1826 pub fn reverse_bits(self) -> Self {
1827 unsafe { intrinsics::bitreverse(self as $ActualT) as Self }
1831 concat!("Converts an integer from big endian to the target's endianness.
1833 On big endian this is a no-op. On little endian the bytes are
1841 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
1843 if cfg!(target_endian = \"big\") {
1844 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
1846 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
1849 #[stable(feature = "rust1", since = "1.0.0")]
1851 pub fn from_be(x: Self) -> Self {
1852 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
1857 concat!("Converts an integer from little endian to the target's endianness.
1859 On little endian this is a no-op. On big endian the bytes are
1867 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
1869 if cfg!(target_endian = \"little\") {
1870 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
1872 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
1875 #[stable(feature = "rust1", since = "1.0.0")]
1877 pub fn from_le(x: Self) -> Self {
1878 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
1883 concat!("Converts `self` to big endian from the target's endianness.
1885 On big endian this is a no-op. On little endian the bytes are
1893 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
1895 if cfg!(target_endian = \"big\") {
1896 assert_eq!(n.to_be(), n)
1898 assert_eq!(n.to_be(), n.swap_bytes())
1901 #[stable(feature = "rust1", since = "1.0.0")]
1903 pub fn to_be(self) -> Self { // or not to be?
1904 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
1909 concat!("Converts `self` to little endian from the target's endianness.
1911 On little endian this is a no-op. On big endian the bytes are
1919 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
1921 if cfg!(target_endian = \"little\") {
1922 assert_eq!(n.to_le(), n)
1924 assert_eq!(n.to_le(), n.swap_bytes())
1927 #[stable(feature = "rust1", since = "1.0.0")]
1929 pub fn to_le(self) -> Self {
1930 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
1935 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
1936 if overflow occurred.
1943 ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), ",
1944 "Some(", stringify!($SelfT), "::max_value() - 1));
1945 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3),None);", $EndFeature, "
1947 #[stable(feature = "rust1", since = "1.0.0")]
1949 pub fn checked_add(self, rhs: Self) -> Option<Self> {
1950 let (a, b) = self.overflowing_add(rhs);
1951 if b {None} else {Some(a)}
1956 concat!("Checked integer subtraction. Computes `self - rhs`, returning
1957 `None` if overflow occurred.
1964 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
1965 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
1967 #[stable(feature = "rust1", since = "1.0.0")]
1969 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
1970 let (a, b) = self.overflowing_sub(rhs);
1971 if b {None} else {Some(a)}
1976 concat!("Checked integer multiplication. Computes `self * rhs`, returning
1977 `None` if overflow occurred.
1984 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
1985 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, "
1987 #[stable(feature = "rust1", since = "1.0.0")]
1989 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
1990 let (a, b) = self.overflowing_mul(rhs);
1991 if b {None} else {Some(a)}
1996 concat!("Checked integer division. Computes `self / rhs`, returning `None`
2004 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2005 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2007 #[stable(feature = "rust1", since = "1.0.0")]
2009 pub fn checked_div(self, rhs: Self) -> Option<Self> {
2012 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
2018 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
2026 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
2027 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
2029 #[stable(feature = "wrapping", since = "1.7.0")]
2031 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
2035 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
2041 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
2044 Note that negating any positive integer will overflow.
2051 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
2052 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
2054 #[stable(feature = "wrapping", since = "1.7.0")]
2056 pub fn checked_neg(self) -> Option<Self> {
2057 let (a, b) = self.overflowing_neg();
2058 if b {None} else {Some(a)}
2063 concat!("Checked shift left. Computes `self << rhs`, returning `None`
2064 if `rhs` is larger than or equal to the number of bits in `self`.
2071 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
2072 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
2074 #[stable(feature = "wrapping", since = "1.7.0")]
2076 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
2077 let (a, b) = self.overflowing_shl(rhs);
2078 if b {None} else {Some(a)}
2083 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
2084 if `rhs` is larger than or equal to the number of bits in `self`.
2091 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
2092 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
2094 #[stable(feature = "wrapping", since = "1.7.0")]
2096 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
2097 let (a, b) = self.overflowing_shr(rhs);
2098 if b {None} else {Some(a)}
2103 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
2111 #![feature(no_panic_pow)]
2112 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
2113 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, "
2115 #[unstable(feature = "no_panic_pow", issue = "48320")]
2117 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
2118 let mut base = self;
2119 let mut acc: Self = 1;
2123 acc = acc.checked_mul(base)?;
2126 base = base.checked_mul(base)?;
2129 // Deal with the final bit of the exponent separately, since
2130 // squaring the base afterwards is not necessary and may cause a
2131 // needless overflow.
2133 acc = acc.checked_mul(base)?;
2141 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
2142 the numeric bounds instead of overflowing.
2149 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
2150 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
2152 #[stable(feature = "rust1", since = "1.0.0")]
2154 pub fn saturating_add(self, rhs: Self) -> Self {
2155 match self.checked_add(rhs) {
2157 None => Self::max_value(),
2163 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
2164 at the numeric bounds instead of overflowing.
2171 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
2172 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
2174 #[stable(feature = "rust1", since = "1.0.0")]
2176 pub fn saturating_sub(self, rhs: Self) -> Self {
2177 match self.checked_sub(rhs) {
2179 None => Self::min_value(),
2185 concat!("Saturating integer multiplication. Computes `self * rhs`,
2186 saturating at the numeric bounds instead of overflowing.
2193 ", $Feature, "use std::", stringify!($SelfT), ";
2195 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
2196 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
2197 "::MAX);", $EndFeature, "
2199 #[stable(feature = "wrapping", since = "1.7.0")]
2201 pub fn saturating_mul(self, rhs: Self) -> Self {
2202 self.checked_mul(rhs).unwrap_or(Self::max_value())
2207 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
2208 saturating at the numeric bounds instead of overflowing.
2215 #![feature(no_panic_pow)]
2216 ", $Feature, "use std::", stringify!($SelfT), ";
2218 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
2219 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
2222 #[unstable(feature = "no_panic_pow", issue = "48320")]
2224 pub fn saturating_pow(self, exp: u32) -> Self {
2225 match self.checked_pow(exp) {
2227 None => Self::max_value(),
2233 concat!("Wrapping (modular) addition. Computes `self + rhs`,
2234 wrapping around at the boundary of the type.
2241 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
2242 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
2245 #[stable(feature = "rust1", since = "1.0.0")]
2247 pub fn wrapping_add(self, rhs: Self) -> Self {
2249 intrinsics::overflowing_add(self, rhs)
2255 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
2256 wrapping around at the boundary of the type.
2263 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
2264 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
2267 #[stable(feature = "rust1", since = "1.0.0")]
2269 pub fn wrapping_sub(self, rhs: Self) -> Self {
2271 intrinsics::overflowing_sub(self, rhs)
2276 /// Wrapping (modular) multiplication. Computes `self *
2277 /// rhs`, wrapping around at the boundary of the type.
2283 /// Please note that this example is shared between integer types.
2284 /// Which explains why `u8` is used here.
2287 /// assert_eq!(10u8.wrapping_mul(12), 120);
2288 /// assert_eq!(25u8.wrapping_mul(12), 44);
2290 #[stable(feature = "rust1", since = "1.0.0")]
2292 pub fn wrapping_mul(self, rhs: Self) -> Self {
2294 intrinsics::overflowing_mul(self, rhs)
2299 concat!("Wrapping (modular) division. Computes `self / rhs`.
2300 Wrapped division on unsigned types is just normal division.
2301 There's no way wrapping could ever happen.
2302 This function exists, so that all operations
2303 are accounted for in the wrapping operations.
2310 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
2312 #[stable(feature = "num_wrapping", since = "1.2.0")]
2314 pub fn wrapping_div(self, rhs: Self) -> Self {
2320 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
2321 Wrapped remainder calculation on unsigned types is
2322 just the regular remainder calculation.
2323 There's no way wrapping could ever happen.
2324 This function exists, so that all operations
2325 are accounted for in the wrapping operations.
2332 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
2334 #[stable(feature = "num_wrapping", since = "1.2.0")]
2336 pub fn wrapping_rem(self, rhs: Self) -> Self {
2341 /// Wrapping (modular) negation. Computes `-self`,
2342 /// wrapping around at the boundary of the type.
2344 /// Since unsigned types do not have negative equivalents
2345 /// all applications of this function will wrap (except for `-0`).
2346 /// For values smaller than the corresponding signed type's maximum
2347 /// the result is the same as casting the corresponding signed value.
2348 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
2349 /// `MAX` is the corresponding signed type's maximum.
2355 /// Please note that this example is shared between integer types.
2356 /// Which explains why `i8` is used here.
2359 /// assert_eq!(100i8.wrapping_neg(), -100);
2360 /// assert_eq!((-128i8).wrapping_neg(), -128);
2362 #[stable(feature = "num_wrapping", since = "1.2.0")]
2364 pub fn wrapping_neg(self) -> Self {
2365 self.overflowing_neg().0
2369 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
2370 where `mask` removes any high-order bits of `rhs` that
2371 would cause the shift to exceed the bitwidth of the type.
2373 Note that this is *not* the same as a rotate-left; the
2374 RHS of a wrapping shift-left is restricted to the range
2375 of the type, rather than the bits shifted out of the LHS
2376 being returned to the other end. The primitive integer
2377 types all implement a `rotate_left` function, which may
2378 be what you want instead.
2385 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
2386 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
2388 #[stable(feature = "num_wrapping", since = "1.2.0")]
2390 pub fn wrapping_shl(self, rhs: u32) -> Self {
2392 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
2398 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
2399 where `mask` removes any high-order bits of `rhs` that
2400 would cause the shift to exceed the bitwidth of the type.
2402 Note that this is *not* the same as a rotate-right; the
2403 RHS of a wrapping shift-right is restricted to the range
2404 of the type, rather than the bits shifted out of the LHS
2405 being returned to the other end. The primitive integer
2406 types all implement a `rotate_right` function, which may
2407 be what you want instead.
2414 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
2415 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
2417 #[stable(feature = "num_wrapping", since = "1.2.0")]
2419 pub fn wrapping_shr(self, rhs: u32) -> Self {
2421 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
2427 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
2428 wrapping around at the boundary of the type.
2435 #![feature(no_panic_pow)]
2436 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
2437 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
2439 #[unstable(feature = "no_panic_pow", issue = "48320")]
2441 pub fn wrapping_pow(self, mut exp: u32) -> Self {
2442 let mut base = self;
2443 let mut acc: Self = 1;
2447 acc = acc.wrapping_mul(base);
2450 base = base.wrapping_mul(base);
2453 // Deal with the final bit of the exponent separately, since
2454 // squaring the base afterwards is not necessary and may cause a
2455 // needless overflow.
2457 acc = acc.wrapping_mul(base);
2465 concat!("Calculates `self` + `rhs`
2467 Returns a tuple of the addition along with a boolean indicating
2468 whether an arithmetic overflow would occur. If an overflow would
2469 have occurred then the wrapped value is returned.
2476 ", $Feature, "use std::", stringify!($SelfT), ";
2478 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
2479 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
2482 #[stable(feature = "wrapping", since = "1.7.0")]
2483 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
2484 let (a, b) = unsafe {
2485 intrinsics::add_with_overflow(self as $ActualT,
2493 concat!("Calculates `self` - `rhs`
2495 Returns a tuple of the subtraction along with a boolean indicating
2496 whether an arithmetic overflow would occur. If an overflow would
2497 have occurred then the wrapped value is returned.
2504 ", $Feature, "use std::", stringify!($SelfT), ";
2506 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
2507 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
2511 #[stable(feature = "wrapping", since = "1.7.0")]
2512 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
2513 let (a, b) = unsafe {
2514 intrinsics::sub_with_overflow(self as $ActualT,
2521 /// Calculates the multiplication of `self` and `rhs`.
2523 /// Returns a tuple of the multiplication along with a boolean
2524 /// indicating whether an arithmetic overflow would occur. If an
2525 /// overflow would have occurred then the wrapped value is returned.
2531 /// Please note that this example is shared between integer types.
2532 /// Which explains why `u32` is used here.
2535 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
2536 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
2539 #[stable(feature = "wrapping", since = "1.7.0")]
2540 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
2541 let (a, b) = unsafe {
2542 intrinsics::mul_with_overflow(self as $ActualT,
2549 concat!("Calculates the divisor when `self` is divided by `rhs`.
2551 Returns a tuple of the divisor along with a boolean indicating
2552 whether an arithmetic overflow would occur. Note that for unsigned
2553 integers overflow never occurs, so the second value is always
2558 This function will panic if `rhs` is 0.
2565 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
2568 #[stable(feature = "wrapping", since = "1.7.0")]
2569 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
2575 concat!("Calculates the remainder when `self` is divided by `rhs`.
2577 Returns a tuple of the remainder after dividing along with a boolean
2578 indicating whether an arithmetic overflow would occur. Note that for
2579 unsigned integers overflow never occurs, so the second value is
2584 This function will panic if `rhs` is 0.
2591 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
2594 #[stable(feature = "wrapping", since = "1.7.0")]
2595 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
2601 concat!("Negates self in an overflowing fashion.
2603 Returns `!self + 1` using wrapping operations to return the value
2604 that represents the negation of this unsigned value. Note that for
2605 positive unsigned values overflow always occurs, but negating 0 does
2613 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
2614 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
2615 ", true));", $EndFeature, "
2618 #[stable(feature = "wrapping", since = "1.7.0")]
2619 pub fn overflowing_neg(self) -> (Self, bool) {
2620 ((!self).wrapping_add(1), self != 0)
2625 concat!("Shifts self left by `rhs` bits.
2627 Returns a tuple of the shifted version of self along with a boolean
2628 indicating whether the shift value was larger than or equal to the
2629 number of bits. If the shift value is too large, then value is
2630 masked (N-1) where N is the number of bits, and this value is then
2631 used to perform the shift.
2638 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
2639 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
2642 #[stable(feature = "wrapping", since = "1.7.0")]
2643 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
2644 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
2649 concat!("Shifts self right by `rhs` bits.
2651 Returns a tuple of the shifted version of self along with a boolean
2652 indicating whether the shift value was larger than or equal to the
2653 number of bits. If the shift value is too large, then value is
2654 masked (N-1) where N is the number of bits, and this value is then
2655 used to perform the shift.
2662 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
2663 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
2666 #[stable(feature = "wrapping", since = "1.7.0")]
2667 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
2668 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
2673 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
2675 Returns a tuple of the exponentiation along with a bool indicating
2676 whether an overflow happened.
2683 #![feature(no_panic_pow)]
2684 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
2685 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
2687 #[unstable(feature = "no_panic_pow", issue = "48320")]
2689 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
2690 let mut base = self;
2691 let mut acc: Self = 1;
2692 let mut overflown = false;
2693 // Scratch space for storing results of overflowing_mul.
2698 r = acc.overflowing_mul(base);
2703 r = base.overflowing_mul(base);
2708 // Deal with the final bit of the exponent separately, since
2709 // squaring the base afterwards is not necessary and may cause a
2710 // needless overflow.
2712 r = acc.overflowing_mul(base);
2722 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
2729 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
2731 #[stable(feature = "rust1", since = "1.0.0")]
2733 #[rustc_inherit_overflow_checks]
2734 pub fn pow(self, mut exp: u32) -> Self {
2735 let mut base = self;
2746 // Deal with the final bit of the exponent separately, since
2747 // squaring the base afterwards is not necessary and may cause a
2748 // needless overflow.
2758 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
2765 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
2766 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
2768 #[stable(feature = "rust1", since = "1.0.0")]
2770 pub fn is_power_of_two(self) -> bool {
2771 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
2775 // Returns one less than next power of two.
2776 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
2778 // 8u8.one_less_than_next_power_of_two() == 7
2779 // 6u8.one_less_than_next_power_of_two() == 7
2781 // This method cannot overflow, as in the `next_power_of_two`
2782 // overflow cases it instead ends up returning the maximum value
2783 // of the type, and can return 0 for 0.
2785 fn one_less_than_next_power_of_two(self) -> Self {
2786 if self <= 1 { return 0; }
2788 // Because `p > 0`, it cannot consist entirely of leading zeros.
2789 // That means the shift is always in-bounds, and some processors
2790 // (such as intel pre-haswell) have more efficient ctlz
2791 // intrinsics when the argument is non-zero.
2793 let z = unsafe { intrinsics::ctlz_nonzero(p) };
2794 <$SelfT>::max_value() >> z
2798 concat!("Returns the smallest power of two greater than or equal to `self`.
2800 When return value overflows (i.e. `self > (1 << (N-1))` for type
2801 `uN`), it panics in debug mode and return value is wrapped to 0 in
2802 release mode (the only situation in which method can return 0).
2809 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
2810 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
2812 #[stable(feature = "rust1", since = "1.0.0")]
2814 pub fn next_power_of_two(self) -> Self {
2815 // Call the trait to get overflow checks
2816 ops::Add::add(self.one_less_than_next_power_of_two(), 1)
2821 concat!("Returns the smallest power of two greater than or equal to `n`. If
2822 the next power of two is greater than the type's maximum value,
2823 `None` is returned, otherwise the power of two is wrapped in `Some`.
2830 ", $Feature, "assert_eq!(2", stringify!($SelfT),
2831 ".checked_next_power_of_two(), Some(2));
2832 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
2833 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
2836 #[stable(feature = "rust1", since = "1.0.0")]
2837 pub fn checked_next_power_of_two(self) -> Option<Self> {
2838 self.one_less_than_next_power_of_two().checked_add(1)
2846 uint_impl! { u8, u8, 8, 255, "", "" }
2849 /// Checks if the value is within the ASCII range.
2854 /// let ascii = 97u8;
2855 /// let non_ascii = 150u8;
2857 /// assert!(ascii.is_ascii());
2858 /// assert!(!non_ascii.is_ascii());
2860 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2862 pub fn is_ascii(&self) -> bool {
2866 /// Makes a copy of the value in its ASCII upper case equivalent.
2868 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2869 /// but non-ASCII letters are unchanged.
2871 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
2876 /// let lowercase_a = 97u8;
2878 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
2881 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
2882 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2884 pub fn to_ascii_uppercase(&self) -> u8 {
2885 ASCII_UPPERCASE_MAP[*self as usize]
2888 /// Makes a copy of the value in its ASCII lower case equivalent.
2890 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2891 /// but non-ASCII letters are unchanged.
2893 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
2898 /// let uppercase_a = 65u8;
2900 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
2903 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
2904 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2906 pub fn to_ascii_lowercase(&self) -> u8 {
2907 ASCII_LOWERCASE_MAP[*self as usize]
2910 /// Checks that two values are an ASCII case-insensitive match.
2912 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
2917 /// let lowercase_a = 97u8;
2918 /// let uppercase_a = 65u8;
2920 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
2922 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2924 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
2925 self.to_ascii_lowercase() == other.to_ascii_lowercase()
2928 /// Converts this value to its ASCII upper case equivalent in-place.
2930 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2931 /// but non-ASCII letters are unchanged.
2933 /// To return a new uppercased value without modifying the existing one, use
2934 /// [`to_ascii_uppercase`].
2939 /// let mut byte = b'a';
2941 /// byte.make_ascii_uppercase();
2943 /// assert_eq!(b'A', byte);
2946 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
2947 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2949 pub fn make_ascii_uppercase(&mut self) {
2950 *self = self.to_ascii_uppercase();
2953 /// Converts this value to its ASCII lower case equivalent in-place.
2955 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2956 /// but non-ASCII letters are unchanged.
2958 /// To return a new lowercased value without modifying the existing one, use
2959 /// [`to_ascii_lowercase`].
2964 /// let mut byte = b'A';
2966 /// byte.make_ascii_lowercase();
2968 /// assert_eq!(b'a', byte);
2971 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
2972 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2974 pub fn make_ascii_lowercase(&mut self) {
2975 *self = self.to_ascii_lowercase();
2978 /// Checks if the value is an ASCII alphabetic character:
2980 /// - U+0041 'A' ... U+005A 'Z', or
2981 /// - U+0061 'a' ... U+007A 'z'.
2986 /// #![feature(ascii_ctype)]
2988 /// let uppercase_a = b'A';
2989 /// let uppercase_g = b'G';
2992 /// let zero = b'0';
2993 /// let percent = b'%';
2994 /// let space = b' ';
2996 /// let esc = 0x1b_u8;
2998 /// assert!(uppercase_a.is_ascii_alphabetic());
2999 /// assert!(uppercase_g.is_ascii_alphabetic());
3000 /// assert!(a.is_ascii_alphabetic());
3001 /// assert!(g.is_ascii_alphabetic());
3002 /// assert!(!zero.is_ascii_alphabetic());
3003 /// assert!(!percent.is_ascii_alphabetic());
3004 /// assert!(!space.is_ascii_alphabetic());
3005 /// assert!(!lf.is_ascii_alphabetic());
3006 /// assert!(!esc.is_ascii_alphabetic());
3008 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3010 pub fn is_ascii_alphabetic(&self) -> bool {
3011 if *self >= 0x80 { return false; }
3012 match ASCII_CHARACTER_CLASS[*self as usize] {
3013 L | Lx | U | Ux => true,
3018 /// Checks if the value is an ASCII uppercase character:
3019 /// U+0041 'A' ... U+005A 'Z'.
3024 /// #![feature(ascii_ctype)]
3026 /// let uppercase_a = b'A';
3027 /// let uppercase_g = b'G';
3030 /// let zero = b'0';
3031 /// let percent = b'%';
3032 /// let space = b' ';
3034 /// let esc = 0x1b_u8;
3036 /// assert!(uppercase_a.is_ascii_uppercase());
3037 /// assert!(uppercase_g.is_ascii_uppercase());
3038 /// assert!(!a.is_ascii_uppercase());
3039 /// assert!(!g.is_ascii_uppercase());
3040 /// assert!(!zero.is_ascii_uppercase());
3041 /// assert!(!percent.is_ascii_uppercase());
3042 /// assert!(!space.is_ascii_uppercase());
3043 /// assert!(!lf.is_ascii_uppercase());
3044 /// assert!(!esc.is_ascii_uppercase());
3046 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3048 pub fn is_ascii_uppercase(&self) -> bool {
3049 if *self >= 0x80 { return false }
3050 match ASCII_CHARACTER_CLASS[*self as usize] {
3056 /// Checks if the value is an ASCII lowercase character:
3057 /// U+0061 'a' ... U+007A 'z'.
3062 /// #![feature(ascii_ctype)]
3064 /// let uppercase_a = b'A';
3065 /// let uppercase_g = b'G';
3068 /// let zero = b'0';
3069 /// let percent = b'%';
3070 /// let space = b' ';
3072 /// let esc = 0x1b_u8;
3074 /// assert!(!uppercase_a.is_ascii_lowercase());
3075 /// assert!(!uppercase_g.is_ascii_lowercase());
3076 /// assert!(a.is_ascii_lowercase());
3077 /// assert!(g.is_ascii_lowercase());
3078 /// assert!(!zero.is_ascii_lowercase());
3079 /// assert!(!percent.is_ascii_lowercase());
3080 /// assert!(!space.is_ascii_lowercase());
3081 /// assert!(!lf.is_ascii_lowercase());
3082 /// assert!(!esc.is_ascii_lowercase());
3084 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3086 pub fn is_ascii_lowercase(&self) -> bool {
3087 if *self >= 0x80 { return false }
3088 match ASCII_CHARACTER_CLASS[*self as usize] {
3094 /// Checks if the value is an ASCII alphanumeric character:
3096 /// - U+0041 'A' ... U+005A 'Z', or
3097 /// - U+0061 'a' ... U+007A 'z', or
3098 /// - U+0030 '0' ... U+0039 '9'.
3103 /// #![feature(ascii_ctype)]
3105 /// let uppercase_a = b'A';
3106 /// let uppercase_g = b'G';
3109 /// let zero = b'0';
3110 /// let percent = b'%';
3111 /// let space = b' ';
3113 /// let esc = 0x1b_u8;
3115 /// assert!(uppercase_a.is_ascii_alphanumeric());
3116 /// assert!(uppercase_g.is_ascii_alphanumeric());
3117 /// assert!(a.is_ascii_alphanumeric());
3118 /// assert!(g.is_ascii_alphanumeric());
3119 /// assert!(zero.is_ascii_alphanumeric());
3120 /// assert!(!percent.is_ascii_alphanumeric());
3121 /// assert!(!space.is_ascii_alphanumeric());
3122 /// assert!(!lf.is_ascii_alphanumeric());
3123 /// assert!(!esc.is_ascii_alphanumeric());
3125 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3127 pub fn is_ascii_alphanumeric(&self) -> bool {
3128 if *self >= 0x80 { return false }
3129 match ASCII_CHARACTER_CLASS[*self as usize] {
3130 D | L | Lx | U | Ux => true,
3135 /// Checks if the value is an ASCII decimal digit:
3136 /// U+0030 '0' ... U+0039 '9'.
3141 /// #![feature(ascii_ctype)]
3143 /// let uppercase_a = b'A';
3144 /// let uppercase_g = b'G';
3147 /// let zero = b'0';
3148 /// let percent = b'%';
3149 /// let space = b' ';
3151 /// let esc = 0x1b_u8;
3153 /// assert!(!uppercase_a.is_ascii_digit());
3154 /// assert!(!uppercase_g.is_ascii_digit());
3155 /// assert!(!a.is_ascii_digit());
3156 /// assert!(!g.is_ascii_digit());
3157 /// assert!(zero.is_ascii_digit());
3158 /// assert!(!percent.is_ascii_digit());
3159 /// assert!(!space.is_ascii_digit());
3160 /// assert!(!lf.is_ascii_digit());
3161 /// assert!(!esc.is_ascii_digit());
3163 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3165 pub fn is_ascii_digit(&self) -> bool {
3166 if *self >= 0x80 { return false }
3167 match ASCII_CHARACTER_CLASS[*self as usize] {
3173 /// Checks if the value is an ASCII hexadecimal digit:
3175 /// - U+0030 '0' ... U+0039 '9', or
3176 /// - U+0041 'A' ... U+0046 'F', or
3177 /// - U+0061 'a' ... U+0066 'f'.
3182 /// #![feature(ascii_ctype)]
3184 /// let uppercase_a = b'A';
3185 /// let uppercase_g = b'G';
3188 /// let zero = b'0';
3189 /// let percent = b'%';
3190 /// let space = b' ';
3192 /// let esc = 0x1b_u8;
3194 /// assert!(uppercase_a.is_ascii_hexdigit());
3195 /// assert!(!uppercase_g.is_ascii_hexdigit());
3196 /// assert!(a.is_ascii_hexdigit());
3197 /// assert!(!g.is_ascii_hexdigit());
3198 /// assert!(zero.is_ascii_hexdigit());
3199 /// assert!(!percent.is_ascii_hexdigit());
3200 /// assert!(!space.is_ascii_hexdigit());
3201 /// assert!(!lf.is_ascii_hexdigit());
3202 /// assert!(!esc.is_ascii_hexdigit());
3204 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3206 pub fn is_ascii_hexdigit(&self) -> bool {
3207 if *self >= 0x80 { return false }
3208 match ASCII_CHARACTER_CLASS[*self as usize] {
3209 D | Lx | Ux => true,
3214 /// Checks if the value is an ASCII punctuation character:
3216 /// - U+0021 ... U+002F `! " # $ % & ' ( ) * + , - . /`, or
3217 /// - U+003A ... U+0040 `: ; < = > ? @`, or
3218 /// - U+005B ... U+0060 ``[ \ ] ^ _ ` ``, or
3219 /// - U+007B ... U+007E `{ | } ~`
3224 /// #![feature(ascii_ctype)]
3226 /// let uppercase_a = b'A';
3227 /// let uppercase_g = b'G';
3230 /// let zero = b'0';
3231 /// let percent = b'%';
3232 /// let space = b' ';
3234 /// let esc = 0x1b_u8;
3236 /// assert!(!uppercase_a.is_ascii_punctuation());
3237 /// assert!(!uppercase_g.is_ascii_punctuation());
3238 /// assert!(!a.is_ascii_punctuation());
3239 /// assert!(!g.is_ascii_punctuation());
3240 /// assert!(!zero.is_ascii_punctuation());
3241 /// assert!(percent.is_ascii_punctuation());
3242 /// assert!(!space.is_ascii_punctuation());
3243 /// assert!(!lf.is_ascii_punctuation());
3244 /// assert!(!esc.is_ascii_punctuation());
3246 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3248 pub fn is_ascii_punctuation(&self) -> bool {
3249 if *self >= 0x80 { return false }
3250 match ASCII_CHARACTER_CLASS[*self as usize] {
3256 /// Checks if the value is an ASCII graphic character:
3257 /// U+0021 '!' ... U+007E '~'.
3262 /// #![feature(ascii_ctype)]
3264 /// let uppercase_a = b'A';
3265 /// let uppercase_g = b'G';
3268 /// let zero = b'0';
3269 /// let percent = b'%';
3270 /// let space = b' ';
3272 /// let esc = 0x1b_u8;
3274 /// assert!(uppercase_a.is_ascii_graphic());
3275 /// assert!(uppercase_g.is_ascii_graphic());
3276 /// assert!(a.is_ascii_graphic());
3277 /// assert!(g.is_ascii_graphic());
3278 /// assert!(zero.is_ascii_graphic());
3279 /// assert!(percent.is_ascii_graphic());
3280 /// assert!(!space.is_ascii_graphic());
3281 /// assert!(!lf.is_ascii_graphic());
3282 /// assert!(!esc.is_ascii_graphic());
3284 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3286 pub fn is_ascii_graphic(&self) -> bool {
3287 if *self >= 0x80 { return false; }
3288 match ASCII_CHARACTER_CLASS[*self as usize] {
3289 Ux | U | Lx | L | D | P => true,
3294 /// Checks if the value is an ASCII whitespace character:
3295 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
3296 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
3298 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
3299 /// whitespace][infra-aw]. There are several other definitions in
3300 /// wide use. For instance, [the POSIX locale][pct] includes
3301 /// U+000B VERTICAL TAB as well as all the above characters,
3302 /// but—from the very same specification—[the default rule for
3303 /// "field splitting" in the Bourne shell][bfs] considers *only*
3304 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
3306 /// If you are writing a program that will process an existing
3307 /// file format, check what that format's definition of whitespace is
3308 /// before using this function.
3310 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
3311 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
3312 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
3317 /// #![feature(ascii_ctype)]
3319 /// let uppercase_a = b'A';
3320 /// let uppercase_g = b'G';
3323 /// let zero = b'0';
3324 /// let percent = b'%';
3325 /// let space = b' ';
3327 /// let esc = 0x1b_u8;
3329 /// assert!(!uppercase_a.is_ascii_whitespace());
3330 /// assert!(!uppercase_g.is_ascii_whitespace());
3331 /// assert!(!a.is_ascii_whitespace());
3332 /// assert!(!g.is_ascii_whitespace());
3333 /// assert!(!zero.is_ascii_whitespace());
3334 /// assert!(!percent.is_ascii_whitespace());
3335 /// assert!(space.is_ascii_whitespace());
3336 /// assert!(lf.is_ascii_whitespace());
3337 /// assert!(!esc.is_ascii_whitespace());
3339 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3341 pub fn is_ascii_whitespace(&self) -> bool {
3342 if *self >= 0x80 { return false; }
3343 match ASCII_CHARACTER_CLASS[*self as usize] {
3349 /// Checks if the value is an ASCII control character:
3350 /// U+0000 NUL ... U+001F UNIT SEPARATOR, or U+007F DELETE.
3351 /// Note that most ASCII whitespace characters are control
3352 /// characters, but SPACE is not.
3357 /// #![feature(ascii_ctype)]
3359 /// let uppercase_a = b'A';
3360 /// let uppercase_g = b'G';
3363 /// let zero = b'0';
3364 /// let percent = b'%';
3365 /// let space = b' ';
3367 /// let esc = 0x1b_u8;
3369 /// assert!(!uppercase_a.is_ascii_control());
3370 /// assert!(!uppercase_g.is_ascii_control());
3371 /// assert!(!a.is_ascii_control());
3372 /// assert!(!g.is_ascii_control());
3373 /// assert!(!zero.is_ascii_control());
3374 /// assert!(!percent.is_ascii_control());
3375 /// assert!(!space.is_ascii_control());
3376 /// assert!(lf.is_ascii_control());
3377 /// assert!(esc.is_ascii_control());
3379 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3381 pub fn is_ascii_control(&self) -> bool {
3382 if *self >= 0x80 { return false; }
3383 match ASCII_CHARACTER_CLASS[*self as usize] {
3392 uint_impl! { u16, u16, 16, 65535, "", "" }
3397 uint_impl! { u32, u32, 32, 4294967295, "", "" }
3402 uint_impl! { u64, u64, 64, 18446744073709551615, "", "" }
3407 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "#![feature(i128_type)]
3415 #[cfg(target_pointer_width = "16")]
3418 uint_impl! { usize, u16, 16, 65536, "", "" }
3420 #[cfg(target_pointer_width = "32")]
3423 uint_impl! { usize, u32, 32, 4294967295, "", "" }
3426 #[cfg(target_pointer_width = "64")]
3429 uint_impl! { usize, u64, 64, 18446744073709551615, "", "" }
3432 /// A classification of floating point numbers.
3434 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
3435 /// their documentation for more.
3437 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
3438 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
3443 /// use std::num::FpCategory;
3446 /// let num = 12.4_f32;
3447 /// let inf = f32::INFINITY;
3448 /// let zero = 0f32;
3449 /// let sub: f32 = 1.1754942e-38;
3450 /// let nan = f32::NAN;
3452 /// assert_eq!(num.classify(), FpCategory::Normal);
3453 /// assert_eq!(inf.classify(), FpCategory::Infinite);
3454 /// assert_eq!(zero.classify(), FpCategory::Zero);
3455 /// assert_eq!(nan.classify(), FpCategory::Nan);
3456 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
3458 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
3459 #[stable(feature = "rust1", since = "1.0.0")]
3460 pub enum FpCategory {
3461 /// "Not a Number", often obtained by dividing by zero.
3462 #[stable(feature = "rust1", since = "1.0.0")]
3465 /// Positive or negative infinity.
3466 #[stable(feature = "rust1", since = "1.0.0")]
3469 /// Positive or negative zero.
3470 #[stable(feature = "rust1", since = "1.0.0")]
3473 /// De-normalized floating point representation (less precise than `Normal`).
3474 #[stable(feature = "rust1", since = "1.0.0")]
3477 /// A regular floating point number.
3478 #[stable(feature = "rust1", since = "1.0.0")]
3482 /// A built-in floating point number.
3484 #[unstable(feature = "core_float",
3485 reason = "stable interface is via `impl f{32,64}` in later crates",
3487 pub trait Float: Sized {
3488 /// Type used by `to_bits` and `from_bits`.
3489 #[stable(feature = "core_float_bits", since = "1.25.0")]
3492 /// Returns `true` if this value is NaN and false otherwise.
3493 #[stable(feature = "core", since = "1.6.0")]
3494 fn is_nan(self) -> bool;
3495 /// Returns `true` if this value is positive infinity or negative infinity and
3496 /// false otherwise.
3497 #[stable(feature = "core", since = "1.6.0")]
3498 fn is_infinite(self) -> bool;
3499 /// Returns `true` if this number is neither infinite nor NaN.
3500 #[stable(feature = "core", since = "1.6.0")]
3501 fn is_finite(self) -> bool;
3502 /// Returns `true` if this number is neither zero, infinite, denormal, or NaN.
3503 #[stable(feature = "core", since = "1.6.0")]
3504 fn is_normal(self) -> bool;
3505 /// Returns the category that this number falls into.
3506 #[stable(feature = "core", since = "1.6.0")]
3507 fn classify(self) -> FpCategory;
3509 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
3510 /// number is `Float::nan()`.
3511 #[stable(feature = "core", since = "1.6.0")]
3512 fn abs(self) -> Self;
3513 /// Returns a number that represents the sign of `self`.
3515 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
3516 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
3517 /// - `Float::nan()` if the number is `Float::nan()`
3518 #[stable(feature = "core", since = "1.6.0")]
3519 fn signum(self) -> Self;
3521 /// Returns `true` if `self` is positive, including `+0.0` and
3522 /// `Float::infinity()`.
3523 #[stable(feature = "core", since = "1.6.0")]
3524 fn is_sign_positive(self) -> bool;
3525 /// Returns `true` if `self` is negative, including `-0.0` and
3526 /// `Float::neg_infinity()`.
3527 #[stable(feature = "core", since = "1.6.0")]
3528 fn is_sign_negative(self) -> bool;
3530 /// Take the reciprocal (inverse) of a number, `1/x`.
3531 #[stable(feature = "core", since = "1.6.0")]
3532 fn recip(self) -> Self;
3534 /// Raise a number to an integer power.
3536 /// Using this function is generally faster than using `powf`
3537 #[stable(feature = "core", since = "1.6.0")]
3538 fn powi(self, n: i32) -> Self;
3540 /// Convert radians to degrees.
3541 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
3542 fn to_degrees(self) -> Self;
3543 /// Convert degrees to radians.
3544 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
3545 fn to_radians(self) -> Self;
3547 /// Returns the maximum of the two numbers.
3548 #[stable(feature = "core_float_min_max", since="1.20.0")]
3549 fn max(self, other: Self) -> Self;
3550 /// Returns the minimum of the two numbers.
3551 #[stable(feature = "core_float_min_max", since="1.20.0")]
3552 fn min(self, other: Self) -> Self;
3554 /// Raw transmutation to integer.
3555 #[stable(feature = "core_float_bits", since="1.25.0")]
3556 fn to_bits(self) -> Self::Bits;
3557 /// Raw transmutation from integer.
3558 #[stable(feature = "core_float_bits", since="1.25.0")]
3559 fn from_bits(v: Self::Bits) -> Self;
3562 macro_rules! from_str_radix_int_impl {
3564 #[stable(feature = "rust1", since = "1.0.0")]
3565 impl FromStr for $t {
3566 type Err = ParseIntError;
3567 fn from_str(src: &str) -> Result<Self, ParseIntError> {
3568 from_str_radix(src, 10)
3573 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
3575 /// The error type returned when a checked integral type conversion fails.
3576 #[unstable(feature = "try_from", issue = "33417")]
3577 #[derive(Debug, Copy, Clone)]
3578 pub struct TryFromIntError(());
3580 impl TryFromIntError {
3581 #[unstable(feature = "int_error_internals",
3582 reason = "available through Error trait and this method should \
3583 not be exposed publicly",
3586 pub fn __description(&self) -> &str {
3587 "out of range integral type conversion attempted"
3591 #[unstable(feature = "try_from", issue = "33417")]
3592 impl fmt::Display for TryFromIntError {
3593 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3594 self.__description().fmt(fmt)
3598 #[unstable(feature = "try_from", issue = "33417")]
3599 impl From<Infallible> for TryFromIntError {
3600 fn from(infallible: Infallible) -> TryFromIntError {
3606 // no possible bounds violation
3607 macro_rules! try_from_unbounded {
3608 ($source:ty, $($target:ty),*) => {$(
3609 #[unstable(feature = "try_from", issue = "33417")]
3610 impl TryFrom<$source> for $target {
3611 type Error = Infallible;
3614 fn try_from(value: $source) -> Result<Self, Self::Error> {
3615 Ok(value as $target)
3621 // only negative bounds
3622 macro_rules! try_from_lower_bounded {
3623 ($source:ty, $($target:ty),*) => {$(
3624 #[unstable(feature = "try_from", issue = "33417")]
3625 impl TryFrom<$source> for $target {
3626 type Error = TryFromIntError;
3629 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
3633 Err(TryFromIntError(()))
3640 // unsigned to signed (only positive bound)
3641 macro_rules! try_from_upper_bounded {
3642 ($source:ty, $($target:ty),*) => {$(
3643 #[unstable(feature = "try_from", issue = "33417")]
3644 impl TryFrom<$source> for $target {
3645 type Error = TryFromIntError;
3648 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
3649 if u > (<$target>::max_value() as $source) {
3650 Err(TryFromIntError(()))
3660 macro_rules! try_from_both_bounded {
3661 ($source:ty, $($target:ty),*) => {$(
3662 #[unstable(feature = "try_from", issue = "33417")]
3663 impl TryFrom<$source> for $target {
3664 type Error = TryFromIntError;
3667 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
3668 let min = <$target>::min_value() as $source;
3669 let max = <$target>::max_value() as $source;
3670 if u < min || u > max {
3671 Err(TryFromIntError(()))
3681 ($mac:ident, $source:ty, $($target:ty),*) => {$(
3682 $mac!($target, $source);
3686 /// intra-sign conversions
3687 try_from_upper_bounded!(u16, u8);
3688 try_from_upper_bounded!(u32, u16, u8);
3689 try_from_upper_bounded!(u64, u32, u16, u8);
3690 try_from_upper_bounded!(u128, u64, u32, u16, u8);
3692 try_from_both_bounded!(i16, i8);
3693 try_from_both_bounded!(i32, i16, i8);
3694 try_from_both_bounded!(i64, i32, i16, i8);
3695 try_from_both_bounded!(i128, i64, i32, i16, i8);
3697 // unsigned-to-signed
3698 try_from_upper_bounded!(u8, i8);
3699 try_from_upper_bounded!(u16, i8, i16);
3700 try_from_upper_bounded!(u32, i8, i16, i32);
3701 try_from_upper_bounded!(u64, i8, i16, i32, i64);
3702 try_from_upper_bounded!(u128, i8, i16, i32, i64, i128);
3704 // signed-to-unsigned
3705 try_from_lower_bounded!(i8, u8, u16, u32, u64, u128);
3706 try_from_lower_bounded!(i16, u16, u32, u64, u128);
3707 try_from_lower_bounded!(i32, u32, u64, u128);
3708 try_from_lower_bounded!(i64, u64, u128);
3709 try_from_lower_bounded!(i128, u128);
3710 try_from_both_bounded!(i16, u8);
3711 try_from_both_bounded!(i32, u16, u8);
3712 try_from_both_bounded!(i64, u32, u16, u8);
3713 try_from_both_bounded!(i128, u64, u32, u16, u8);
3716 try_from_upper_bounded!(usize, isize);
3717 try_from_lower_bounded!(isize, usize);
3719 #[cfg(target_pointer_width = "16")]
3720 mod ptr_try_from_impls {
3721 use super::TryFromIntError;
3722 use convert::{Infallible, TryFrom};
3724 try_from_upper_bounded!(usize, u8);
3725 try_from_unbounded!(usize, u16, u32, u64, u128);
3726 try_from_upper_bounded!(usize, i8, i16);
3727 try_from_unbounded!(usize, i32, i64, i128);
3729 try_from_both_bounded!(isize, u8);
3730 try_from_lower_bounded!(isize, u16, u32, u64, u128);
3731 try_from_both_bounded!(isize, i8);
3732 try_from_unbounded!(isize, i16, i32, i64, i128);
3734 rev!(try_from_unbounded, usize, u16);
3735 rev!(try_from_upper_bounded, usize, u32, u64, u128);
3736 rev!(try_from_lower_bounded, usize, i8, i16);
3737 rev!(try_from_both_bounded, usize, i32, i64, i128);
3739 rev!(try_from_unbounded, isize, u8);
3740 rev!(try_from_upper_bounded, isize, u16, u32, u64, u128);
3741 rev!(try_from_unbounded, isize, i16);
3742 rev!(try_from_both_bounded, isize, i32, i64, i128);
3745 #[cfg(target_pointer_width = "32")]
3746 mod ptr_try_from_impls {
3747 use super::TryFromIntError;
3748 use convert::{Infallible, TryFrom};
3750 try_from_upper_bounded!(usize, u8, u16);
3751 try_from_unbounded!(usize, u32, u64, u128);
3752 try_from_upper_bounded!(usize, i8, i16, i32);
3753 try_from_unbounded!(usize, i64, i128);
3755 try_from_both_bounded!(isize, u8, u16);
3756 try_from_lower_bounded!(isize, u32, u64, u128);
3757 try_from_both_bounded!(isize, i8, i16);
3758 try_from_unbounded!(isize, i32, i64, i128);
3760 rev!(try_from_unbounded, usize, u16, u32);
3761 rev!(try_from_upper_bounded, usize, u64, u128);
3762 rev!(try_from_lower_bounded, usize, i8, i16, i32);
3763 rev!(try_from_both_bounded, usize, i64, i128);
3765 rev!(try_from_unbounded, isize, u8, u16);
3766 rev!(try_from_upper_bounded, isize, u32, u64, u128);
3767 rev!(try_from_unbounded, isize, i16, i32);
3768 rev!(try_from_both_bounded, isize, i64, i128);
3771 #[cfg(target_pointer_width = "64")]
3772 mod ptr_try_from_impls {
3773 use super::TryFromIntError;
3774 use convert::{Infallible, TryFrom};
3776 try_from_upper_bounded!(usize, u8, u16, u32);
3777 try_from_unbounded!(usize, u64, u128);
3778 try_from_upper_bounded!(usize, i8, i16, i32, i64);
3779 try_from_unbounded!(usize, i128);
3781 try_from_both_bounded!(isize, u8, u16, u32);
3782 try_from_lower_bounded!(isize, u64, u128);
3783 try_from_both_bounded!(isize, i8, i16, i32);
3784 try_from_unbounded!(isize, i64, i128);
3786 rev!(try_from_unbounded, usize, u16, u32, u64);
3787 rev!(try_from_upper_bounded, usize, u128);
3788 rev!(try_from_lower_bounded, usize, i8, i16, i32, i64);
3789 rev!(try_from_both_bounded, usize, i128);
3791 rev!(try_from_unbounded, isize, u8, u16, u32);
3792 rev!(try_from_upper_bounded, isize, u64, u128);
3793 rev!(try_from_unbounded, isize, i16, i32, i64);
3794 rev!(try_from_both_bounded, isize, i128);
3798 trait FromStrRadixHelper: PartialOrd + Copy {
3799 fn min_value() -> Self;
3800 fn max_value() -> Self;
3801 fn from_u32(u: u32) -> Self;
3802 fn checked_mul(&self, other: u32) -> Option<Self>;
3803 fn checked_sub(&self, other: u32) -> Option<Self>;
3804 fn checked_add(&self, other: u32) -> Option<Self>;
3808 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
3810 fn min_value() -> Self { Self::min_value() }
3812 fn max_value() -> Self { Self::max_value() }
3814 fn from_u32(u: u32) -> Self { u as Self }
3816 fn checked_mul(&self, other: u32) -> Option<Self> {
3817 Self::checked_mul(*self, other as Self)
3820 fn checked_sub(&self, other: u32) -> Option<Self> {
3821 Self::checked_sub(*self, other as Self)
3824 fn checked_add(&self, other: u32) -> Option<Self> {
3825 Self::checked_add(*self, other as Self)
3829 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
3831 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
3832 use self::IntErrorKind::*;
3833 use self::ParseIntError as PIE;
3835 assert!(radix >= 2 && radix <= 36,
3836 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
3840 return Err(PIE { kind: Empty });
3843 let is_signed_ty = T::from_u32(0) > T::min_value();
3845 // all valid digits are ascii, so we will just iterate over the utf8 bytes
3846 // and cast them to chars. .to_digit() will safely return None for anything
3847 // other than a valid ascii digit for the given radix, including the first-byte
3848 // of multi-byte sequences
3849 let src = src.as_bytes();
3851 let (is_positive, digits) = match src[0] {
3852 b'+' => (true, &src[1..]),
3853 b'-' if is_signed_ty => (false, &src[1..]),
3857 if digits.is_empty() {
3858 return Err(PIE { kind: Empty });
3861 let mut result = T::from_u32(0);
3863 // The number is positive
3865 let x = match (c as char).to_digit(radix) {
3867 None => return Err(PIE { kind: InvalidDigit }),
3869 result = match result.checked_mul(radix) {
3870 Some(result) => result,
3871 None => return Err(PIE { kind: Overflow }),
3873 result = match result.checked_add(x) {
3874 Some(result) => result,
3875 None => return Err(PIE { kind: Overflow }),
3879 // The number is negative
3881 let x = match (c as char).to_digit(radix) {
3883 None => return Err(PIE { kind: InvalidDigit }),
3885 result = match result.checked_mul(radix) {
3886 Some(result) => result,
3887 None => return Err(PIE { kind: Underflow }),
3889 result = match result.checked_sub(x) {
3890 Some(result) => result,
3891 None => return Err(PIE { kind: Underflow }),
3898 /// An error which can be returned when parsing an integer.
3900 /// This error is used as the error type for the `from_str_radix()` functions
3901 /// on the primitive integer types, such as [`i8::from_str_radix`].
3903 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
3904 #[derive(Debug, Clone, PartialEq, Eq)]
3905 #[stable(feature = "rust1", since = "1.0.0")]
3906 pub struct ParseIntError {
3910 #[derive(Debug, Clone, PartialEq, Eq)]
3918 impl ParseIntError {
3919 #[unstable(feature = "int_error_internals",
3920 reason = "available through Error trait and this method should \
3921 not be exposed publicly",
3924 pub fn __description(&self) -> &str {
3926 IntErrorKind::Empty => "cannot parse integer from empty string",
3927 IntErrorKind::InvalidDigit => "invalid digit found in string",
3928 IntErrorKind::Overflow => "number too large to fit in target type",
3929 IntErrorKind::Underflow => "number too small to fit in target type",
3934 #[stable(feature = "rust1", since = "1.0.0")]
3935 impl fmt::Display for ParseIntError {
3936 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3937 self.__description().fmt(f)
3941 #[stable(feature = "rust1", since = "1.0.0")]
3942 pub use num::dec2flt::ParseFloatError;
3944 // Conversion traits for primitive integer and float types
3945 // Conversions T -> T are covered by a blanket impl and therefore excluded
3946 // Some conversions from and to usize/isize are not implemented due to portability concerns
3947 macro_rules! impl_from {
3948 ($Small: ty, $Large: ty, #[$attr:meta]) => {
3950 impl From<$Small> for $Large {
3952 fn from(small: $Small) -> $Large {
3959 // Unsigned -> Unsigned
3960 impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3961 impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3962 impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3963 impl_from! { u8, u128, #[unstable(feature = "i128", issue = "35118")] }
3964 impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3965 impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3966 impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3967 impl_from! { u16, u128, #[unstable(feature = "i128", issue = "35118")] }
3968 impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3969 impl_from! { u32, u128, #[unstable(feature = "i128", issue = "35118")] }
3970 impl_from! { u64, u128, #[unstable(feature = "i128", issue = "35118")] }
3973 impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3974 impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3975 impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3976 impl_from! { i8, i128, #[unstable(feature = "i128", issue = "35118")] }
3977 impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3978 impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3979 impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3980 impl_from! { i16, i128, #[unstable(feature = "i128", issue = "35118")] }
3981 impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3982 impl_from! { i32, i128, #[unstable(feature = "i128", issue = "35118")] }
3983 impl_from! { i64, i128, #[unstable(feature = "i128", issue = "35118")] }
3985 // Unsigned -> Signed
3986 impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3987 impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3988 impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3989 impl_from! { u8, i128, #[unstable(feature = "i128", issue = "35118")] }
3990 impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3991 impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3992 impl_from! { u16, i128, #[unstable(feature = "i128", issue = "35118")] }
3993 impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3994 impl_from! { u32, i128, #[unstable(feature = "i128", issue = "35118")] }
3995 impl_from! { u64, i128, #[unstable(feature = "i128", issue = "35118")] }
3997 // Note: integers can only be represented with full precision in a float if
3998 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
3999 // Lossy float conversions are not implemented at this time.
4002 impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4003 impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4004 impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4005 impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4006 impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4008 // Unsigned -> Float
4009 impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4010 impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4011 impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4012 impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4013 impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4016 impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4018 static ASCII_LOWERCASE_MAP: [u8; 256] = [
4019 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4020 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4021 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4022 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4023 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4024 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4025 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4026 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4029 b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4030 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4031 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4034 b'[', b'\\', b']', b'^', b'_',
4035 b'`', b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4036 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4037 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4038 b'x', b'y', b'z', b'{', b'|', b'}', b'~', 0x7f,
4039 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4040 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4041 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4042 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4043 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4044 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4045 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4046 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4047 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4048 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4049 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4050 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4051 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4052 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4053 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4054 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4057 static ASCII_UPPERCASE_MAP: [u8; 256] = [
4058 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4059 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4060 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4061 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4062 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4063 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4064 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4065 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4066 b'@', b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4067 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4068 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4069 b'X', b'Y', b'Z', b'[', b'\\', b']', b'^', b'_',
4072 b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4073 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4074 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4077 b'{', b'|', b'}', b'~', 0x7f,
4078 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4079 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4080 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4081 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4082 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4083 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4084 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4085 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4086 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4087 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4088 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4089 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4090 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4091 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4092 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4093 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4096 enum AsciiCharacterClass {
4098 Cw, // control whitespace
4102 Lx, // lowercase hex digit
4104 Ux, // uppercase hex digit
4107 use self::AsciiCharacterClass::*;
4109 static ASCII_CHARACTER_CLASS: [AsciiCharacterClass; 128] = [
4110 // _0 _1 _2 _3 _4 _5 _6 _7 _8 _9 _a _b _c _d _e _f
4111 C, C, C, C, C, C, C, C, C, Cw,Cw,C, Cw,Cw,C, C, // 0_
4112 C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, // 1_
4113 W, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, // 2_
4114 D, D, D, D, D, D, D, D, D, D, P, P, P, P, P, P, // 3_
4115 P, Ux,Ux,Ux,Ux,Ux,Ux,U, U, U, U, U, U, U, U, U, // 4_
4116 U, U, U, U, U, U, U, U, U, U, U, P, P, P, P, P, // 5_
4117 P, Lx,Lx,Lx,Lx,Lx,Lx,L, L, L, L, L, L, L, L, L, // 6_
4118 L, L, L, L, L, L, L, L, L, L, L, P, P, P, P, C, // 7_