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
325 concat!("Converts an integer from big endian to the target's endianness.
327 On big endian this is a no-op. On little endian the bytes are swapped.
334 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
336 if cfg!(target_endian = \"big\") {
337 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
339 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
343 #[stable(feature = "rust1", since = "1.0.0")]
345 pub fn from_be(x: Self) -> Self {
346 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
351 concat!("Converts an integer from little endian to the target's endianness.
353 On little endian this is a no-op. On big endian the bytes are swapped.
360 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
362 if cfg!(target_endian = \"little\") {
363 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
365 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
369 #[stable(feature = "rust1", since = "1.0.0")]
371 pub fn from_le(x: Self) -> Self {
372 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
377 concat!("Converts `self` to big endian from the target's endianness.
379 On big endian this is a no-op. On little endian the bytes are swapped.
386 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
388 if cfg!(target_endian = \"big\") {
389 assert_eq!(n.to_be(), n)
391 assert_eq!(n.to_be(), n.swap_bytes())
395 #[stable(feature = "rust1", since = "1.0.0")]
397 pub fn to_be(self) -> Self { // or not to be?
398 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
403 concat!("Converts `self` to little endian from the target's endianness.
405 On little endian this is a no-op. On big endian the bytes are swapped.
412 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
414 if cfg!(target_endian = \"little\") {
415 assert_eq!(n.to_le(), n)
417 assert_eq!(n.to_le(), n.swap_bytes())
421 #[stable(feature = "rust1", since = "1.0.0")]
423 pub fn to_le(self) -> Self {
424 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
429 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
430 if overflow occurred.
437 ", $Feature, "assert_eq!((", stringify!($SelfT),
438 "::max_value() - 2).checked_add(1), Some(", stringify!($SelfT), "::max_value() - 1));
439 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);",
442 #[stable(feature = "rust1", since = "1.0.0")]
444 pub fn checked_add(self, rhs: Self) -> Option<Self> {
445 let (a, b) = self.overflowing_add(rhs);
446 if b {None} else {Some(a)}
451 concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
459 ", $Feature, "assert_eq!((", stringify!($SelfT),
460 "::min_value() + 2).checked_sub(1), Some(", stringify!($SelfT), "::min_value() + 1));
461 assert_eq!((", stringify!($SelfT), "::min_value() + 2).checked_sub(3), None);",
464 #[stable(feature = "rust1", since = "1.0.0")]
466 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
467 let (a, b) = self.overflowing_sub(rhs);
468 if b {None} else {Some(a)}
473 concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
481 ", $Feature, "assert_eq!(", stringify!($SelfT),
482 "::max_value().checked_mul(1), Some(", stringify!($SelfT), "::max_value()));
483 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);",
486 #[stable(feature = "rust1", since = "1.0.0")]
488 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
489 let (a, b) = self.overflowing_mul(rhs);
490 if b {None} else {Some(a)}
495 concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
496 or the division results in overflow.
503 ", $Feature, "assert_eq!((", stringify!($SelfT),
504 "::min_value() + 1).checked_div(-1), Some(", stringify!($Max), "));
505 assert_eq!(", stringify!($SelfT), "::min_value().checked_div(-1), None);
506 assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
509 #[stable(feature = "rust1", since = "1.0.0")]
511 pub fn checked_div(self, rhs: Self) -> Option<Self> {
512 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
515 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
521 concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
522 `rhs == 0` or the division results in overflow.
529 ", $Feature, "use std::", stringify!($SelfT), ";
531 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
532 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
533 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
536 #[stable(feature = "wrapping", since = "1.7.0")]
538 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
539 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
542 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
548 concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
555 ", $Feature, "use std::", stringify!($SelfT), ";
557 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
558 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
561 #[stable(feature = "wrapping", since = "1.7.0")]
563 pub fn checked_neg(self) -> Option<Self> {
564 let (a, b) = self.overflowing_neg();
565 if b {None} else {Some(a)}
570 concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
571 than or equal to the number of bits in `self`.
578 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
579 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
582 #[stable(feature = "wrapping", since = "1.7.0")]
584 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
585 let (a, b) = self.overflowing_shl(rhs);
586 if b {None} else {Some(a)}
591 concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
592 larger than or equal to the number of bits in `self`.
599 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
600 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
603 #[stable(feature = "wrapping", since = "1.7.0")]
605 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
606 let (a, b) = self.overflowing_shr(rhs);
607 if b {None} else {Some(a)}
612 concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
620 ", $Feature, "use std::", stringify!($SelfT), ";
622 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
623 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
626 #[stable(feature = "no_panic_abs", since = "1.13.0")]
628 pub fn checked_abs(self) -> Option<Self> {
629 if self.is_negative() {
638 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
646 #![feature(no_panic_pow)]
647 ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
648 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);",
652 #[unstable(feature = "no_panic_pow", issue = "48320")]
654 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
656 let mut acc: Self = 1;
660 acc = acc.checked_mul(base)?;
663 base = base.checked_mul(base)?;
666 // Deal with the final bit of the exponent separately, since
667 // squaring the base afterwards is not necessary and may cause a
668 // needless overflow.
670 acc = acc.checked_mul(base)?;
678 concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
679 bounds instead of overflowing.
686 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
687 assert_eq!(", stringify!($SelfT), "::max_value().saturating_add(100), ", stringify!($SelfT),
691 #[stable(feature = "rust1", since = "1.0.0")]
693 pub fn saturating_add(self, rhs: Self) -> Self {
694 match self.checked_add(rhs) {
696 None if rhs >= 0 => Self::max_value(),
697 None => Self::min_value(),
703 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
704 numeric bounds instead of overflowing.
711 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
712 assert_eq!(", stringify!($SelfT), "::min_value().saturating_sub(100), ", stringify!($SelfT),
716 #[stable(feature = "rust1", since = "1.0.0")]
718 pub fn saturating_sub(self, rhs: Self) -> Self {
719 match self.checked_sub(rhs) {
721 None if rhs >= 0 => Self::min_value(),
722 None => Self::max_value(),
728 concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
729 numeric bounds instead of overflowing.
736 ", $Feature, "use std::", stringify!($SelfT), ";
738 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
739 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
740 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
743 #[stable(feature = "wrapping", since = "1.7.0")]
745 pub fn saturating_mul(self, rhs: Self) -> Self {
746 self.checked_mul(rhs).unwrap_or_else(|| {
747 if (self < 0 && rhs < 0) || (self > 0 && rhs > 0) {
757 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
758 saturating at the numeric bounds instead of overflowing.
765 #![feature(no_panic_pow)]
766 ", $Feature, "use std::", stringify!($SelfT), ";
768 assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
769 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
770 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
773 #[unstable(feature = "no_panic_pow", issue = "48320")]
775 pub fn saturating_pow(self, exp: u32) -> Self {
776 match self.checked_pow(exp) {
778 None if self < 0 && exp % 2 == 1 => Self::min_value(),
779 None => Self::max_value(),
785 concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
786 boundary of the type.
793 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
794 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_add(2), ", stringify!($SelfT),
795 "::min_value() + 1);",
798 #[stable(feature = "rust1", since = "1.0.0")]
800 pub fn wrapping_add(self, rhs: Self) -> Self {
802 intrinsics::overflowing_add(self, rhs)
808 concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
809 boundary of the type.
816 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
817 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::max_value()), ",
818 stringify!($SelfT), "::max_value());",
821 #[stable(feature = "rust1", since = "1.0.0")]
823 pub fn wrapping_sub(self, rhs: Self) -> Self {
825 intrinsics::overflowing_sub(self, rhs)
831 concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
832 the boundary of the type.
839 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
840 assert_eq!(11i8.wrapping_mul(12), -124);",
843 #[stable(feature = "rust1", since = "1.0.0")]
845 pub fn wrapping_mul(self, rhs: Self) -> Self {
847 intrinsics::overflowing_mul(self, rhs)
853 concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
854 boundary of the type.
856 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
857 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
858 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
862 This function will panic if `rhs` is 0.
869 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
870 assert_eq!((-128i8).wrapping_div(-1), -128);",
873 #[stable(feature = "num_wrapping", since = "1.2.0")]
875 pub fn wrapping_div(self, rhs: Self) -> Self {
876 self.overflowing_div(rhs).0
881 concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
882 boundary of the type.
884 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
885 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
886 this function returns `0`.
890 This function will panic if `rhs` is 0.
897 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
898 assert_eq!((-128i8).wrapping_rem(-1), 0);",
901 #[stable(feature = "num_wrapping", since = "1.2.0")]
903 pub fn wrapping_rem(self, rhs: Self) -> Self {
904 self.overflowing_rem(rhs).0
909 concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
912 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
913 is the negative minimal value for the type); this is a positive value that is too large to represent
914 in the type. In such a case, this function returns `MIN` itself.
921 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
922 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_neg(), ", stringify!($SelfT),
926 #[stable(feature = "num_wrapping", since = "1.2.0")]
928 pub fn wrapping_neg(self) -> Self {
929 self.overflowing_neg().0
934 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
935 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
937 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
938 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
939 The primitive integer types all implement a `rotate_left` function, which may be what you want
947 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
948 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
951 #[stable(feature = "num_wrapping", since = "1.2.0")]
953 pub fn wrapping_shl(self, rhs: u32) -> Self {
955 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
961 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
962 removes 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-right; the RHS of a wrapping shift-right is restricted
965 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
966 end. The primitive integer types all implement a `rotate_right` function, which may be what you want
974 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
975 assert_eq!((-128i16).wrapping_shr(64), -128);",
978 #[stable(feature = "num_wrapping", since = "1.2.0")]
980 pub fn wrapping_shr(self, rhs: u32) -> Self {
982 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
988 concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
989 the boundary of the type.
991 The only case where such wrapping can occur is when one takes the absolute value of the negative
992 minimal value for the type this is a positive value that is too large to represent in the type. In
993 such a case, this function returns `MIN` itself.
1000 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
1001 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
1002 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_abs(), ", stringify!($SelfT),
1004 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1007 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1009 pub fn wrapping_abs(self) -> Self {
1010 if self.is_negative() {
1019 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1020 wrapping around at the boundary of the type.
1027 #![feature(no_panic_pow)]
1028 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);
1029 assert_eq!(3i8.wrapping_pow(5), -13);
1030 assert_eq!(3i8.wrapping_pow(6), -39);",
1033 #[unstable(feature = "no_panic_pow", issue = "48320")]
1035 pub fn wrapping_pow(self, mut exp: u32) -> Self {
1036 let mut base = self;
1037 let mut acc: Self = 1;
1041 acc = acc.wrapping_mul(base);
1044 base = base.wrapping_mul(base);
1047 // Deal with the final bit of the exponent separately, since
1048 // squaring the base afterwards is not necessary and may cause a
1049 // needless overflow.
1051 acc = acc.wrapping_mul(base);
1059 concat!("Calculates `self` + `rhs`
1061 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1062 occur. If an overflow would have occurred then the wrapped value is returned.
1069 ", $Feature, "use std::", stringify!($SelfT), ";
1071 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1072 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
1073 "::MIN, true));", $EndFeature, "
1076 #[stable(feature = "wrapping", since = "1.7.0")]
1077 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1078 let (a, b) = unsafe {
1079 intrinsics::add_with_overflow(self as $ActualT,
1087 concat!("Calculates `self` - `rhs`
1089 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1090 would occur. If an overflow would have occurred then the wrapped value is returned.
1097 ", $Feature, "use std::", stringify!($SelfT), ";
1099 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
1100 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
1101 "::MAX, true));", $EndFeature, "
1104 #[stable(feature = "wrapping", since = "1.7.0")]
1105 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1106 let (a, b) = unsafe {
1107 intrinsics::sub_with_overflow(self as $ActualT,
1115 concat!("Calculates the multiplication of `self` and `rhs`.
1117 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1118 would occur. If an overflow would have occurred then the wrapped value is returned.
1125 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1126 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1130 #[stable(feature = "wrapping", since = "1.7.0")]
1131 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1132 let (a, b) = unsafe {
1133 intrinsics::mul_with_overflow(self as $ActualT,
1141 concat!("Calculates the divisor when `self` is divided by `rhs`.
1143 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1144 occur. If an overflow would occur then self is returned.
1148 This function will panic if `rhs` is 0.
1155 ", $Feature, "use std::", stringify!($SelfT), ";
1157 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1158 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1163 #[stable(feature = "wrapping", since = "1.7.0")]
1164 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1165 if self == Self::min_value() && rhs == -1 {
1174 concat!("Calculates the remainder when `self` is divided by `rhs`.
1176 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1177 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1181 This function will panic if `rhs` is 0.
1188 ", $Feature, "use std::", stringify!($SelfT), ";
1190 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1191 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1195 #[stable(feature = "wrapping", since = "1.7.0")]
1196 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1197 if self == Self::min_value() && rhs == -1 {
1206 concat!("Negates self, overflowing if this is equal to the minimum value.
1208 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1209 happened. If `self` is the minimum value (e.g. `i32::MIN` for values of type `i32`), then the
1210 minimum value will be returned again and `true` will be returned for an overflow happening.
1217 ", $Feature, "use std::", stringify!($SelfT), ";
1219 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1220 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1221 "::MIN, true));", $EndFeature, "
1224 #[stable(feature = "wrapping", since = "1.7.0")]
1225 pub fn overflowing_neg(self) -> (Self, bool) {
1226 if self == Self::min_value() {
1227 (Self::min_value(), true)
1235 concat!("Shifts self left by `rhs` bits.
1237 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1238 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1239 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1246 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1247 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1251 #[stable(feature = "wrapping", since = "1.7.0")]
1252 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1253 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1258 concat!("Shifts self right by `rhs` bits.
1260 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1261 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1262 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1269 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1270 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1274 #[stable(feature = "wrapping", since = "1.7.0")]
1275 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1276 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1281 concat!("Computes the absolute value of `self`.
1283 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1284 happened. If self is the minimum value (e.g. ", stringify!($SelfT), "::MIN for values of type
1285 ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1286 for an overflow happening.
1293 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1294 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1295 assert_eq!((", stringify!($SelfT), "::min_value()).overflowing_abs(), (", stringify!($SelfT),
1296 "::min_value(), true));",
1299 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1301 pub fn overflowing_abs(self) -> (Self, bool) {
1302 if self.is_negative() {
1303 self.overflowing_neg()
1311 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1313 Returns a tuple of the exponentiation along with a bool indicating
1314 whether an overflow happened.
1321 #![feature(no_panic_pow)]
1322 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));
1323 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
1326 #[unstable(feature = "no_panic_pow", issue = "48320")]
1328 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1329 let mut base = self;
1330 let mut acc: Self = 1;
1331 let mut overflown = false;
1332 // Scratch space for storing results of overflowing_mul.
1337 r = acc.overflowing_mul(base);
1342 r = base.overflowing_mul(base);
1347 // Deal with the final bit of the exponent separately, since
1348 // squaring the base afterwards is not necessary and may cause a
1349 // needless overflow.
1351 r = acc.overflowing_mul(base);
1361 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1368 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
1370 assert_eq!(x.pow(5), 32);",
1373 #[stable(feature = "rust1", since = "1.0.0")]
1375 #[rustc_inherit_overflow_checks]
1376 pub fn pow(self, mut exp: u32) -> Self {
1377 let mut base = self;
1388 // Deal with the final bit of the exponent separately, since
1389 // squaring the base afterwards is not necessary and may cause a
1390 // needless overflow.
1400 concat!("Computes the absolute value of `self`.
1404 The absolute value of `", stringify!($SelfT), "::min_value()` cannot be represented as an
1405 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
1406 code in debug mode will trigger a panic on this case and optimized code will return `",
1407 stringify!($SelfT), "::min_value()` without a panic.
1414 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
1415 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
1418 #[stable(feature = "rust1", since = "1.0.0")]
1420 #[rustc_inherit_overflow_checks]
1421 pub fn abs(self) -> Self {
1422 if self.is_negative() {
1423 // Note that the #[inline] above means that the overflow
1424 // semantics of this negation depend on the crate we're being
1434 concat!("Returns a number representing sign of `self`.
1436 - `0` if the number is zero
1437 - `1` if the number is positive
1438 - `-1` if the number is negative
1445 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
1446 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
1447 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
1450 #[stable(feature = "rust1", since = "1.0.0")]
1452 pub fn signum(self) -> Self {
1462 concat!("Returns `true` if `self` is positive and `false` if the number is zero or
1470 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
1471 assert!(!(-10", stringify!($SelfT), ").is_positive());",
1474 #[stable(feature = "rust1", since = "1.0.0")]
1476 pub fn is_positive(self) -> bool { self > 0 }
1480 concat!("Returns `true` if `self` is negative and `false` if the number is zero or
1488 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
1489 assert!(!10", stringify!($SelfT), ".is_negative());",
1492 #[stable(feature = "rust1", since = "1.0.0")]
1494 pub fn is_negative(self) -> bool { self < 0 }
1501 int_impl! { i8, i8, u8, 8, -128, 127, "", "" }
1506 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "" }
1511 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "" }
1516 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "" }
1521 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
1522 170141183460469231731687303715884105727, "#![feature(i128_type)]
1529 #[cfg(target_pointer_width = "16")]
1532 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "" }
1535 #[cfg(target_pointer_width = "32")]
1538 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "" }
1541 #[cfg(target_pointer_width = "64")]
1544 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "" }
1547 // `Int` + `UnsignedInt` implemented for unsigned integers
1548 macro_rules! uint_impl {
1549 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr) => {
1551 concat!("Returns the smallest value that can be represented by this integer type.
1558 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), 0);", $EndFeature, "
1560 #[stable(feature = "rust1", since = "1.0.0")]
1562 pub const fn min_value() -> Self { 0 }
1566 concat!("Returns the largest value that can be represented by this integer type.
1573 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ",
1574 stringify!($MaxV), ");", $EndFeature, "
1576 #[stable(feature = "rust1", since = "1.0.0")]
1578 pub const fn max_value() -> Self { !0 }
1582 concat!("Converts a string slice in a given base to an integer.
1584 The string is expected to be an optional `+` sign
1586 Leading and trailing whitespace represent an error.
1587 Digits are a subset of these characters, depending on `radix`:
1595 This function panics if `radix` is not in the range from 2 to 36.
1602 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
1605 #[stable(feature = "rust1", since = "1.0.0")]
1606 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
1607 from_str_radix(src, radix)
1612 concat!("Returns the number of ones in the binary representation of `self`.
1619 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
1621 assert_eq!(n.count_ones(), 3);", $EndFeature, "
1623 #[stable(feature = "rust1", since = "1.0.0")]
1625 pub fn count_ones(self) -> u32 {
1626 unsafe { intrinsics::ctpop(self as $ActualT) as u32 }
1631 concat!("Returns the number of zeros in the binary representation of `self`.
1638 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 0);", $EndFeature, "
1640 #[stable(feature = "rust1", since = "1.0.0")]
1642 pub fn count_zeros(self) -> u32 {
1643 (!self).count_ones()
1648 concat!("Returns the number of leading zeros in the binary representation of `self`.
1655 ", $Feature, "let n = ", stringify!($SelfT), "::max_value() >> 2;
1657 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
1659 #[stable(feature = "rust1", since = "1.0.0")]
1661 pub fn leading_zeros(self) -> u32 {
1662 unsafe { intrinsics::ctlz(self as $ActualT) as u32 }
1667 concat!("Returns the number of trailing zeros in the binary representation
1675 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
1677 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
1679 #[stable(feature = "rust1", since = "1.0.0")]
1681 pub fn trailing_zeros(self) -> u32 {
1682 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
1683 // emits two conditional moves on x86_64. By promoting the value to
1684 // u16 and setting bit 8, we get better code without any conditional
1686 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
1687 // pending, remove this workaround once LLVM generates better code
1691 intrinsics::cttz(self as u16 | 0x100) as u32
1693 intrinsics::cttz(self) as u32
1699 /// Shifts the bits to the left by a specified amount, `n`,
1700 /// wrapping the truncated bits to the end of the resulting integer.
1702 /// Please note this isn't the same operation as `<<`!
1708 /// Please note that this example is shared between integer types.
1709 /// Which explains why `u64` is used here.
1712 /// let n = 0x0123456789ABCDEFu64;
1713 /// let m = 0x3456789ABCDEF012u64;
1715 /// assert_eq!(n.rotate_left(12), m);
1717 #[stable(feature = "rust1", since = "1.0.0")]
1719 pub fn rotate_left(self, n: u32) -> Self {
1720 // Protect against undefined behaviour for over-long bit shifts
1722 (self << n) | (self >> (($BITS - n) % $BITS))
1725 /// Shifts the bits to the right by a specified amount, `n`,
1726 /// wrapping the truncated bits to the beginning of the resulting
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 = 0xDEF0123456789ABCu64;
1742 /// assert_eq!(n.rotate_right(12), m);
1744 #[stable(feature = "rust1", since = "1.0.0")]
1746 pub fn rotate_right(self, n: u32) -> Self {
1747 // Protect against undefined behaviour for over-long bit shifts
1749 (self >> n) | (self << (($BITS - n) % $BITS))
1752 /// Reverses the byte order of the integer.
1758 /// Please note that this example is shared between integer types.
1759 /// Which explains why `u16` is used here.
1762 /// let n: u16 = 0b0000000_01010101;
1763 /// assert_eq!(n, 85);
1765 /// let m = n.swap_bytes();
1767 /// assert_eq!(m, 0b01010101_00000000);
1768 /// assert_eq!(m, 21760);
1770 #[stable(feature = "rust1", since = "1.0.0")]
1772 pub fn swap_bytes(self) -> Self {
1773 unsafe { intrinsics::bswap(self as $ActualT) as Self }
1777 concat!("Converts an integer from big endian to the target's endianness.
1779 On big endian this is a no-op. On little endian the bytes are
1787 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
1789 if cfg!(target_endian = \"big\") {
1790 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
1792 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
1795 #[stable(feature = "rust1", since = "1.0.0")]
1797 pub fn from_be(x: Self) -> Self {
1798 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
1803 concat!("Converts an integer from little endian to the target's endianness.
1805 On little endian this is a no-op. On big endian the bytes are
1813 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
1815 if cfg!(target_endian = \"little\") {
1816 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
1818 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
1821 #[stable(feature = "rust1", since = "1.0.0")]
1823 pub fn from_le(x: Self) -> Self {
1824 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
1829 concat!("Converts `self` to big endian from the target's endianness.
1831 On big endian this is a no-op. On little endian the bytes are
1839 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
1841 if cfg!(target_endian = \"big\") {
1842 assert_eq!(n.to_be(), n)
1844 assert_eq!(n.to_be(), n.swap_bytes())
1847 #[stable(feature = "rust1", since = "1.0.0")]
1849 pub fn to_be(self) -> Self { // or not to be?
1850 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
1855 concat!("Converts `self` to little endian from the target's endianness.
1857 On little endian this is a no-op. On big endian the bytes are
1865 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
1867 if cfg!(target_endian = \"little\") {
1868 assert_eq!(n.to_le(), n)
1870 assert_eq!(n.to_le(), n.swap_bytes())
1873 #[stable(feature = "rust1", since = "1.0.0")]
1875 pub fn to_le(self) -> Self {
1876 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
1881 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
1882 if overflow occurred.
1889 ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), ",
1890 "Some(", stringify!($SelfT), "::max_value() - 1));
1891 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3),None);", $EndFeature, "
1893 #[stable(feature = "rust1", since = "1.0.0")]
1895 pub fn checked_add(self, rhs: Self) -> Option<Self> {
1896 let (a, b) = self.overflowing_add(rhs);
1897 if b {None} else {Some(a)}
1902 concat!("Checked integer subtraction. Computes `self - rhs`, returning
1903 `None` if overflow occurred.
1910 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
1911 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
1913 #[stable(feature = "rust1", since = "1.0.0")]
1915 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
1916 let (a, b) = self.overflowing_sub(rhs);
1917 if b {None} else {Some(a)}
1922 concat!("Checked integer multiplication. Computes `self * rhs`, returning
1923 `None` if overflow occurred.
1930 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
1931 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, "
1933 #[stable(feature = "rust1", since = "1.0.0")]
1935 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
1936 let (a, b) = self.overflowing_mul(rhs);
1937 if b {None} else {Some(a)}
1942 concat!("Checked integer division. Computes `self / rhs`, returning `None`
1950 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
1951 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
1953 #[stable(feature = "rust1", since = "1.0.0")]
1955 pub fn checked_div(self, rhs: Self) -> Option<Self> {
1958 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
1964 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
1972 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
1973 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
1975 #[stable(feature = "wrapping", since = "1.7.0")]
1977 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
1981 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
1987 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
1990 Note that negating any positive integer will overflow.
1997 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
1998 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
2000 #[stable(feature = "wrapping", since = "1.7.0")]
2002 pub fn checked_neg(self) -> Option<Self> {
2003 let (a, b) = self.overflowing_neg();
2004 if b {None} else {Some(a)}
2009 concat!("Checked shift left. Computes `self << rhs`, returning `None`
2010 if `rhs` is larger than or equal to the number of bits in `self`.
2017 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
2018 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
2020 #[stable(feature = "wrapping", since = "1.7.0")]
2022 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
2023 let (a, b) = self.overflowing_shl(rhs);
2024 if b {None} else {Some(a)}
2029 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
2030 if `rhs` is larger than or equal to the number of bits in `self`.
2037 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
2038 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
2040 #[stable(feature = "wrapping", since = "1.7.0")]
2042 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
2043 let (a, b) = self.overflowing_shr(rhs);
2044 if b {None} else {Some(a)}
2049 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
2057 #![feature(no_panic_pow)]
2058 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
2059 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, "
2061 #[unstable(feature = "no_panic_pow", issue = "48320")]
2063 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
2064 let mut base = self;
2065 let mut acc: Self = 1;
2069 acc = acc.checked_mul(base)?;
2072 base = base.checked_mul(base)?;
2075 // Deal with the final bit of the exponent separately, since
2076 // squaring the base afterwards is not necessary and may cause a
2077 // needless overflow.
2079 acc = acc.checked_mul(base)?;
2087 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
2088 the numeric bounds instead of overflowing.
2095 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
2096 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
2098 #[stable(feature = "rust1", since = "1.0.0")]
2100 pub fn saturating_add(self, rhs: Self) -> Self {
2101 match self.checked_add(rhs) {
2103 None => Self::max_value(),
2109 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
2110 at the numeric bounds instead of overflowing.
2117 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
2118 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
2120 #[stable(feature = "rust1", since = "1.0.0")]
2122 pub fn saturating_sub(self, rhs: Self) -> Self {
2123 match self.checked_sub(rhs) {
2125 None => Self::min_value(),
2131 concat!("Saturating integer multiplication. Computes `self * rhs`,
2132 saturating at the numeric bounds instead of overflowing.
2139 ", $Feature, "use std::", stringify!($SelfT), ";
2141 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
2142 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
2143 "::MAX);", $EndFeature, "
2145 #[stable(feature = "wrapping", since = "1.7.0")]
2147 pub fn saturating_mul(self, rhs: Self) -> Self {
2148 self.checked_mul(rhs).unwrap_or(Self::max_value())
2153 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
2154 saturating at the numeric bounds instead of overflowing.
2161 #![feature(no_panic_pow)]
2162 ", $Feature, "use std::", stringify!($SelfT), ";
2164 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
2165 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
2168 #[unstable(feature = "no_panic_pow", issue = "48320")]
2170 pub fn saturating_pow(self, exp: u32) -> Self {
2171 match self.checked_pow(exp) {
2173 None => Self::max_value(),
2179 concat!("Wrapping (modular) addition. Computes `self + rhs`,
2180 wrapping around at the boundary of the type.
2187 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
2188 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
2191 #[stable(feature = "rust1", since = "1.0.0")]
2193 pub fn wrapping_add(self, rhs: Self) -> Self {
2195 intrinsics::overflowing_add(self, rhs)
2201 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
2202 wrapping around at the boundary of the type.
2209 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
2210 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
2213 #[stable(feature = "rust1", since = "1.0.0")]
2215 pub fn wrapping_sub(self, rhs: Self) -> Self {
2217 intrinsics::overflowing_sub(self, rhs)
2222 /// Wrapping (modular) multiplication. Computes `self *
2223 /// rhs`, wrapping around at the boundary of the type.
2229 /// Please note that this example is shared between integer types.
2230 /// Which explains why `u8` is used here.
2233 /// assert_eq!(10u8.wrapping_mul(12), 120);
2234 /// assert_eq!(25u8.wrapping_mul(12), 44);
2236 #[stable(feature = "rust1", since = "1.0.0")]
2238 pub fn wrapping_mul(self, rhs: Self) -> Self {
2240 intrinsics::overflowing_mul(self, rhs)
2245 concat!("Wrapping (modular) division. Computes `self / rhs`.
2246 Wrapped division on unsigned types is just normal division.
2247 There's no way wrapping could ever happen.
2248 This function exists, so that all operations
2249 are accounted for in the wrapping operations.
2256 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
2258 #[stable(feature = "num_wrapping", since = "1.2.0")]
2260 pub fn wrapping_div(self, rhs: Self) -> Self {
2266 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
2267 Wrapped remainder calculation on unsigned types is
2268 just the regular remainder calculation.
2269 There's no way wrapping could ever happen.
2270 This function exists, so that all operations
2271 are accounted for in the wrapping operations.
2278 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
2280 #[stable(feature = "num_wrapping", since = "1.2.0")]
2282 pub fn wrapping_rem(self, rhs: Self) -> Self {
2287 /// Wrapping (modular) negation. Computes `-self`,
2288 /// wrapping around at the boundary of the type.
2290 /// Since unsigned types do not have negative equivalents
2291 /// all applications of this function will wrap (except for `-0`).
2292 /// For values smaller than the corresponding signed type's maximum
2293 /// the result is the same as casting the corresponding signed value.
2294 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
2295 /// `MAX` is the corresponding signed type's maximum.
2301 /// Please note that this example is shared between integer types.
2302 /// Which explains why `i8` is used here.
2305 /// assert_eq!(100i8.wrapping_neg(), -100);
2306 /// assert_eq!((-128i8).wrapping_neg(), -128);
2308 #[stable(feature = "num_wrapping", since = "1.2.0")]
2310 pub fn wrapping_neg(self) -> Self {
2311 self.overflowing_neg().0
2315 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
2316 where `mask` removes any high-order bits of `rhs` that
2317 would cause the shift to exceed the bitwidth of the type.
2319 Note that this is *not* the same as a rotate-left; the
2320 RHS of a wrapping shift-left is restricted to the range
2321 of the type, rather than the bits shifted out of the LHS
2322 being returned to the other end. The primitive integer
2323 types all implement a `rotate_left` function, which may
2324 be what you want instead.
2331 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
2332 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
2334 #[stable(feature = "num_wrapping", since = "1.2.0")]
2336 pub fn wrapping_shl(self, rhs: u32) -> Self {
2338 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
2344 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
2345 where `mask` removes any high-order bits of `rhs` that
2346 would cause the shift to exceed the bitwidth of the type.
2348 Note that this is *not* the same as a rotate-right; the
2349 RHS of a wrapping shift-right is restricted to the range
2350 of the type, rather than the bits shifted out of the LHS
2351 being returned to the other end. The primitive integer
2352 types all implement a `rotate_right` function, which may
2353 be what you want instead.
2360 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
2361 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
2363 #[stable(feature = "num_wrapping", since = "1.2.0")]
2365 pub fn wrapping_shr(self, rhs: u32) -> Self {
2367 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
2373 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
2374 wrapping around at the boundary of the type.
2381 #![feature(no_panic_pow)]
2382 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
2383 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
2385 #[unstable(feature = "no_panic_pow", issue = "48320")]
2387 pub fn wrapping_pow(self, mut exp: u32) -> Self {
2388 let mut base = self;
2389 let mut acc: Self = 1;
2393 acc = acc.wrapping_mul(base);
2396 base = base.wrapping_mul(base);
2399 // Deal with the final bit of the exponent separately, since
2400 // squaring the base afterwards is not necessary and may cause a
2401 // needless overflow.
2403 acc = acc.wrapping_mul(base);
2411 concat!("Calculates `self` + `rhs`
2413 Returns a tuple of the addition along with a boolean indicating
2414 whether an arithmetic overflow would occur. If an overflow would
2415 have occurred then the wrapped value is returned.
2422 ", $Feature, "use std::", stringify!($SelfT), ";
2424 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
2425 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
2428 #[stable(feature = "wrapping", since = "1.7.0")]
2429 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
2430 let (a, b) = unsafe {
2431 intrinsics::add_with_overflow(self as $ActualT,
2439 concat!("Calculates `self` - `rhs`
2441 Returns a tuple of the subtraction along with a boolean indicating
2442 whether an arithmetic overflow would occur. If an overflow would
2443 have occurred then the wrapped value is returned.
2450 ", $Feature, "use std::", stringify!($SelfT), ";
2452 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
2453 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
2457 #[stable(feature = "wrapping", since = "1.7.0")]
2458 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
2459 let (a, b) = unsafe {
2460 intrinsics::sub_with_overflow(self as $ActualT,
2467 /// Calculates the multiplication of `self` and `rhs`.
2469 /// Returns a tuple of the multiplication along with a boolean
2470 /// indicating whether an arithmetic overflow would occur. If an
2471 /// overflow would have occurred then the wrapped value is returned.
2477 /// Please note that this example is shared between integer types.
2478 /// Which explains why `u32` is used here.
2481 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
2482 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
2485 #[stable(feature = "wrapping", since = "1.7.0")]
2486 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
2487 let (a, b) = unsafe {
2488 intrinsics::mul_with_overflow(self as $ActualT,
2495 concat!("Calculates the divisor when `self` is divided by `rhs`.
2497 Returns a tuple of the divisor along with a boolean indicating
2498 whether an arithmetic overflow would occur. Note that for unsigned
2499 integers overflow never occurs, so the second value is always
2504 This function will panic if `rhs` is 0.
2511 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
2514 #[stable(feature = "wrapping", since = "1.7.0")]
2515 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
2521 concat!("Calculates the remainder when `self` is divided by `rhs`.
2523 Returns a tuple of the remainder after dividing along with a boolean
2524 indicating whether an arithmetic overflow would occur. Note that for
2525 unsigned integers overflow never occurs, so the second value is
2530 This function will panic if `rhs` is 0.
2537 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
2540 #[stable(feature = "wrapping", since = "1.7.0")]
2541 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
2547 concat!("Negates self in an overflowing fashion.
2549 Returns `!self + 1` using wrapping operations to return the value
2550 that represents the negation of this unsigned value. Note that for
2551 positive unsigned values overflow always occurs, but negating 0 does
2559 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
2560 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
2561 ", true));", $EndFeature, "
2564 #[stable(feature = "wrapping", since = "1.7.0")]
2565 pub fn overflowing_neg(self) -> (Self, bool) {
2566 ((!self).wrapping_add(1), self != 0)
2571 concat!("Shifts self left by `rhs` bits.
2573 Returns a tuple of the shifted version of self along with a boolean
2574 indicating whether the shift value was larger than or equal to the
2575 number of bits. If the shift value is too large, then value is
2576 masked (N-1) where N is the number of bits, and this value is then
2577 used to perform the shift.
2584 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
2585 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
2588 #[stable(feature = "wrapping", since = "1.7.0")]
2589 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
2590 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
2595 concat!("Shifts self right by `rhs` bits.
2597 Returns a tuple of the shifted version of self along with a boolean
2598 indicating whether the shift value was larger than or equal to the
2599 number of bits. If the shift value is too large, then value is
2600 masked (N-1) where N is the number of bits, and this value is then
2601 used to perform the shift.
2608 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
2609 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
2612 #[stable(feature = "wrapping", since = "1.7.0")]
2613 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
2614 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
2619 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
2621 Returns a tuple of the exponentiation along with a bool indicating
2622 whether an overflow happened.
2629 #![feature(no_panic_pow)]
2630 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
2631 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
2633 #[unstable(feature = "no_panic_pow", issue = "48320")]
2635 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
2636 let mut base = self;
2637 let mut acc: Self = 1;
2638 let mut overflown = false;
2639 // Scratch space for storing results of overflowing_mul.
2644 r = acc.overflowing_mul(base);
2649 r = base.overflowing_mul(base);
2654 // Deal with the final bit of the exponent separately, since
2655 // squaring the base afterwards is not necessary and may cause a
2656 // needless overflow.
2658 r = acc.overflowing_mul(base);
2668 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
2675 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
2677 #[stable(feature = "rust1", since = "1.0.0")]
2679 #[rustc_inherit_overflow_checks]
2680 pub fn pow(self, mut exp: u32) -> Self {
2681 let mut base = self;
2692 // Deal with the final bit of the exponent separately, since
2693 // squaring the base afterwards is not necessary and may cause a
2694 // needless overflow.
2704 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
2711 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
2712 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
2714 #[stable(feature = "rust1", since = "1.0.0")]
2716 pub fn is_power_of_two(self) -> bool {
2717 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
2721 // Returns one less than next power of two.
2722 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
2724 // 8u8.one_less_than_next_power_of_two() == 7
2725 // 6u8.one_less_than_next_power_of_two() == 7
2727 // This method cannot overflow, as in the `next_power_of_two`
2728 // overflow cases it instead ends up returning the maximum value
2729 // of the type, and can return 0 for 0.
2731 fn one_less_than_next_power_of_two(self) -> Self {
2732 if self <= 1 { return 0; }
2734 // Because `p > 0`, it cannot consist entirely of leading zeros.
2735 // That means the shift is always in-bounds, and some processors
2736 // (such as intel pre-haswell) have more efficient ctlz
2737 // intrinsics when the argument is non-zero.
2739 let z = unsafe { intrinsics::ctlz_nonzero(p) };
2740 <$SelfT>::max_value() >> z
2744 concat!("Returns the smallest power of two greater than or equal to `self`.
2746 When return value overflows (i.e. `self > (1 << (N-1))` for type
2747 `uN`), it panics in debug mode and return value is wrapped to 0 in
2748 release mode (the only situation in which method can return 0).
2755 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
2756 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
2758 #[stable(feature = "rust1", since = "1.0.0")]
2760 pub fn next_power_of_two(self) -> Self {
2761 // Call the trait to get overflow checks
2762 ops::Add::add(self.one_less_than_next_power_of_two(), 1)
2767 concat!("Returns the smallest power of two greater than or equal to `n`. If
2768 the next power of two is greater than the type's maximum value,
2769 `None` is returned, otherwise the power of two is wrapped in `Some`.
2776 ", $Feature, "assert_eq!(2", stringify!($SelfT),
2777 ".checked_next_power_of_two(), Some(2));
2778 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
2779 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
2782 #[stable(feature = "rust1", since = "1.0.0")]
2783 pub fn checked_next_power_of_two(self) -> Option<Self> {
2784 self.one_less_than_next_power_of_two().checked_add(1)
2792 uint_impl! { u8, u8, 8, 255, "", "" }
2795 /// Checks if the value is within the ASCII range.
2800 /// let ascii = 97u8;
2801 /// let non_ascii = 150u8;
2803 /// assert!(ascii.is_ascii());
2804 /// assert!(!non_ascii.is_ascii());
2806 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2808 pub fn is_ascii(&self) -> bool {
2812 /// Makes a copy of the value in its ASCII upper case equivalent.
2814 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2815 /// but non-ASCII letters are unchanged.
2817 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
2822 /// let lowercase_a = 97u8;
2824 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
2827 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
2828 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2830 pub fn to_ascii_uppercase(&self) -> u8 {
2831 ASCII_UPPERCASE_MAP[*self as usize]
2834 /// Makes a copy of the value in its ASCII lower case equivalent.
2836 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2837 /// but non-ASCII letters are unchanged.
2839 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
2844 /// let uppercase_a = 65u8;
2846 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
2849 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
2850 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2852 pub fn to_ascii_lowercase(&self) -> u8 {
2853 ASCII_LOWERCASE_MAP[*self as usize]
2856 /// Checks that two values are an ASCII case-insensitive match.
2858 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
2863 /// let lowercase_a = 97u8;
2864 /// let uppercase_a = 65u8;
2866 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
2868 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2870 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
2871 self.to_ascii_lowercase() == other.to_ascii_lowercase()
2874 /// Converts this value to its ASCII upper case equivalent in-place.
2876 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2877 /// but non-ASCII letters are unchanged.
2879 /// To return a new uppercased value without modifying the existing one, use
2880 /// [`to_ascii_uppercase`].
2885 /// let mut byte = b'a';
2887 /// byte.make_ascii_uppercase();
2889 /// assert_eq!(b'A', byte);
2892 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
2893 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2895 pub fn make_ascii_uppercase(&mut self) {
2896 *self = self.to_ascii_uppercase();
2899 /// Converts this value to its ASCII lower case equivalent in-place.
2901 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2902 /// but non-ASCII letters are unchanged.
2904 /// To return a new lowercased value without modifying the existing one, use
2905 /// [`to_ascii_lowercase`].
2910 /// let mut byte = b'A';
2912 /// byte.make_ascii_lowercase();
2914 /// assert_eq!(b'a', byte);
2917 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
2918 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2920 pub fn make_ascii_lowercase(&mut self) {
2921 *self = self.to_ascii_lowercase();
2924 /// Checks if the value is an ASCII alphabetic character:
2926 /// - U+0041 'A' ... U+005A 'Z', or
2927 /// - U+0061 'a' ... U+007A 'z'.
2932 /// #![feature(ascii_ctype)]
2934 /// let uppercase_a = b'A';
2935 /// let uppercase_g = b'G';
2938 /// let zero = b'0';
2939 /// let percent = b'%';
2940 /// let space = b' ';
2942 /// let esc = 0x1b_u8;
2944 /// assert!(uppercase_a.is_ascii_alphabetic());
2945 /// assert!(uppercase_g.is_ascii_alphabetic());
2946 /// assert!(a.is_ascii_alphabetic());
2947 /// assert!(g.is_ascii_alphabetic());
2948 /// assert!(!zero.is_ascii_alphabetic());
2949 /// assert!(!percent.is_ascii_alphabetic());
2950 /// assert!(!space.is_ascii_alphabetic());
2951 /// assert!(!lf.is_ascii_alphabetic());
2952 /// assert!(!esc.is_ascii_alphabetic());
2954 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2956 pub fn is_ascii_alphabetic(&self) -> bool {
2957 if *self >= 0x80 { return false; }
2958 match ASCII_CHARACTER_CLASS[*self as usize] {
2959 L | Lx | U | Ux => true,
2964 /// Checks if the value is an ASCII uppercase character:
2965 /// U+0041 'A' ... U+005A 'Z'.
2970 /// #![feature(ascii_ctype)]
2972 /// let uppercase_a = b'A';
2973 /// let uppercase_g = b'G';
2976 /// let zero = b'0';
2977 /// let percent = b'%';
2978 /// let space = b' ';
2980 /// let esc = 0x1b_u8;
2982 /// assert!(uppercase_a.is_ascii_uppercase());
2983 /// assert!(uppercase_g.is_ascii_uppercase());
2984 /// assert!(!a.is_ascii_uppercase());
2985 /// assert!(!g.is_ascii_uppercase());
2986 /// assert!(!zero.is_ascii_uppercase());
2987 /// assert!(!percent.is_ascii_uppercase());
2988 /// assert!(!space.is_ascii_uppercase());
2989 /// assert!(!lf.is_ascii_uppercase());
2990 /// assert!(!esc.is_ascii_uppercase());
2992 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2994 pub fn is_ascii_uppercase(&self) -> bool {
2995 if *self >= 0x80 { return false }
2996 match ASCII_CHARACTER_CLASS[*self as usize] {
3002 /// Checks if the value is an ASCII lowercase character:
3003 /// U+0061 'a' ... U+007A 'z'.
3008 /// #![feature(ascii_ctype)]
3010 /// let uppercase_a = b'A';
3011 /// let uppercase_g = b'G';
3014 /// let zero = b'0';
3015 /// let percent = b'%';
3016 /// let space = b' ';
3018 /// let esc = 0x1b_u8;
3020 /// assert!(!uppercase_a.is_ascii_lowercase());
3021 /// assert!(!uppercase_g.is_ascii_lowercase());
3022 /// assert!(a.is_ascii_lowercase());
3023 /// assert!(g.is_ascii_lowercase());
3024 /// assert!(!zero.is_ascii_lowercase());
3025 /// assert!(!percent.is_ascii_lowercase());
3026 /// assert!(!space.is_ascii_lowercase());
3027 /// assert!(!lf.is_ascii_lowercase());
3028 /// assert!(!esc.is_ascii_lowercase());
3030 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3032 pub fn is_ascii_lowercase(&self) -> bool {
3033 if *self >= 0x80 { return false }
3034 match ASCII_CHARACTER_CLASS[*self as usize] {
3040 /// Checks if the value is an ASCII alphanumeric character:
3042 /// - U+0041 'A' ... U+005A 'Z', or
3043 /// - U+0061 'a' ... U+007A 'z', or
3044 /// - U+0030 '0' ... U+0039 '9'.
3049 /// #![feature(ascii_ctype)]
3051 /// let uppercase_a = b'A';
3052 /// let uppercase_g = b'G';
3055 /// let zero = b'0';
3056 /// let percent = b'%';
3057 /// let space = b' ';
3059 /// let esc = 0x1b_u8;
3061 /// assert!(uppercase_a.is_ascii_alphanumeric());
3062 /// assert!(uppercase_g.is_ascii_alphanumeric());
3063 /// assert!(a.is_ascii_alphanumeric());
3064 /// assert!(g.is_ascii_alphanumeric());
3065 /// assert!(zero.is_ascii_alphanumeric());
3066 /// assert!(!percent.is_ascii_alphanumeric());
3067 /// assert!(!space.is_ascii_alphanumeric());
3068 /// assert!(!lf.is_ascii_alphanumeric());
3069 /// assert!(!esc.is_ascii_alphanumeric());
3071 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3073 pub fn is_ascii_alphanumeric(&self) -> bool {
3074 if *self >= 0x80 { return false }
3075 match ASCII_CHARACTER_CLASS[*self as usize] {
3076 D | L | Lx | U | Ux => true,
3081 /// Checks if the value is an ASCII decimal digit:
3082 /// U+0030 '0' ... U+0039 '9'.
3087 /// #![feature(ascii_ctype)]
3089 /// let uppercase_a = b'A';
3090 /// let uppercase_g = b'G';
3093 /// let zero = b'0';
3094 /// let percent = b'%';
3095 /// let space = b' ';
3097 /// let esc = 0x1b_u8;
3099 /// assert!(!uppercase_a.is_ascii_digit());
3100 /// assert!(!uppercase_g.is_ascii_digit());
3101 /// assert!(!a.is_ascii_digit());
3102 /// assert!(!g.is_ascii_digit());
3103 /// assert!(zero.is_ascii_digit());
3104 /// assert!(!percent.is_ascii_digit());
3105 /// assert!(!space.is_ascii_digit());
3106 /// assert!(!lf.is_ascii_digit());
3107 /// assert!(!esc.is_ascii_digit());
3109 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3111 pub fn is_ascii_digit(&self) -> bool {
3112 if *self >= 0x80 { return false }
3113 match ASCII_CHARACTER_CLASS[*self as usize] {
3119 /// Checks if the value is an ASCII hexadecimal digit:
3121 /// - U+0030 '0' ... U+0039 '9', or
3122 /// - U+0041 'A' ... U+0046 'F', or
3123 /// - U+0061 'a' ... U+0066 'f'.
3128 /// #![feature(ascii_ctype)]
3130 /// let uppercase_a = b'A';
3131 /// let uppercase_g = b'G';
3134 /// let zero = b'0';
3135 /// let percent = b'%';
3136 /// let space = b' ';
3138 /// let esc = 0x1b_u8;
3140 /// assert!(uppercase_a.is_ascii_hexdigit());
3141 /// assert!(!uppercase_g.is_ascii_hexdigit());
3142 /// assert!(a.is_ascii_hexdigit());
3143 /// assert!(!g.is_ascii_hexdigit());
3144 /// assert!(zero.is_ascii_hexdigit());
3145 /// assert!(!percent.is_ascii_hexdigit());
3146 /// assert!(!space.is_ascii_hexdigit());
3147 /// assert!(!lf.is_ascii_hexdigit());
3148 /// assert!(!esc.is_ascii_hexdigit());
3150 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3152 pub fn is_ascii_hexdigit(&self) -> bool {
3153 if *self >= 0x80 { return false }
3154 match ASCII_CHARACTER_CLASS[*self as usize] {
3155 D | Lx | Ux => true,
3160 /// Checks if the value is an ASCII punctuation character:
3162 /// - U+0021 ... U+002F `! " # $ % & ' ( ) * + , - . /`, or
3163 /// - U+003A ... U+0040 `: ; < = > ? @`, or
3164 /// - U+005B ... U+0060 ``[ \ ] ^ _ ` ``, or
3165 /// - U+007B ... U+007E `{ | } ~`
3170 /// #![feature(ascii_ctype)]
3172 /// let uppercase_a = b'A';
3173 /// let uppercase_g = b'G';
3176 /// let zero = b'0';
3177 /// let percent = b'%';
3178 /// let space = b' ';
3180 /// let esc = 0x1b_u8;
3182 /// assert!(!uppercase_a.is_ascii_punctuation());
3183 /// assert!(!uppercase_g.is_ascii_punctuation());
3184 /// assert!(!a.is_ascii_punctuation());
3185 /// assert!(!g.is_ascii_punctuation());
3186 /// assert!(!zero.is_ascii_punctuation());
3187 /// assert!(percent.is_ascii_punctuation());
3188 /// assert!(!space.is_ascii_punctuation());
3189 /// assert!(!lf.is_ascii_punctuation());
3190 /// assert!(!esc.is_ascii_punctuation());
3192 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3194 pub fn is_ascii_punctuation(&self) -> bool {
3195 if *self >= 0x80 { return false }
3196 match ASCII_CHARACTER_CLASS[*self as usize] {
3202 /// Checks if the value is an ASCII graphic character:
3203 /// U+0021 '!' ... U+007E '~'.
3208 /// #![feature(ascii_ctype)]
3210 /// let uppercase_a = b'A';
3211 /// let uppercase_g = b'G';
3214 /// let zero = b'0';
3215 /// let percent = b'%';
3216 /// let space = b' ';
3218 /// let esc = 0x1b_u8;
3220 /// assert!(uppercase_a.is_ascii_graphic());
3221 /// assert!(uppercase_g.is_ascii_graphic());
3222 /// assert!(a.is_ascii_graphic());
3223 /// assert!(g.is_ascii_graphic());
3224 /// assert!(zero.is_ascii_graphic());
3225 /// assert!(percent.is_ascii_graphic());
3226 /// assert!(!space.is_ascii_graphic());
3227 /// assert!(!lf.is_ascii_graphic());
3228 /// assert!(!esc.is_ascii_graphic());
3230 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3232 pub fn is_ascii_graphic(&self) -> bool {
3233 if *self >= 0x80 { return false; }
3234 match ASCII_CHARACTER_CLASS[*self as usize] {
3235 Ux | U | Lx | L | D | P => true,
3240 /// Checks if the value is an ASCII whitespace character:
3241 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
3242 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
3244 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
3245 /// whitespace][infra-aw]. There are several other definitions in
3246 /// wide use. For instance, [the POSIX locale][pct] includes
3247 /// U+000B VERTICAL TAB as well as all the above characters,
3248 /// but—from the very same specification—[the default rule for
3249 /// "field splitting" in the Bourne shell][bfs] considers *only*
3250 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
3252 /// If you are writing a program that will process an existing
3253 /// file format, check what that format's definition of whitespace is
3254 /// before using this function.
3256 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
3257 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
3258 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
3263 /// #![feature(ascii_ctype)]
3265 /// let uppercase_a = b'A';
3266 /// let uppercase_g = b'G';
3269 /// let zero = b'0';
3270 /// let percent = b'%';
3271 /// let space = b' ';
3273 /// let esc = 0x1b_u8;
3275 /// assert!(!uppercase_a.is_ascii_whitespace());
3276 /// assert!(!uppercase_g.is_ascii_whitespace());
3277 /// assert!(!a.is_ascii_whitespace());
3278 /// assert!(!g.is_ascii_whitespace());
3279 /// assert!(!zero.is_ascii_whitespace());
3280 /// assert!(!percent.is_ascii_whitespace());
3281 /// assert!(space.is_ascii_whitespace());
3282 /// assert!(lf.is_ascii_whitespace());
3283 /// assert!(!esc.is_ascii_whitespace());
3285 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3287 pub fn is_ascii_whitespace(&self) -> bool {
3288 if *self >= 0x80 { return false; }
3289 match ASCII_CHARACTER_CLASS[*self as usize] {
3295 /// Checks if the value is an ASCII control character:
3296 /// U+0000 NUL ... U+001F UNIT SEPARATOR, or U+007F DELETE.
3297 /// Note that most ASCII whitespace characters are control
3298 /// characters, but SPACE is not.
3303 /// #![feature(ascii_ctype)]
3305 /// let uppercase_a = b'A';
3306 /// let uppercase_g = b'G';
3309 /// let zero = b'0';
3310 /// let percent = b'%';
3311 /// let space = b' ';
3313 /// let esc = 0x1b_u8;
3315 /// assert!(!uppercase_a.is_ascii_control());
3316 /// assert!(!uppercase_g.is_ascii_control());
3317 /// assert!(!a.is_ascii_control());
3318 /// assert!(!g.is_ascii_control());
3319 /// assert!(!zero.is_ascii_control());
3320 /// assert!(!percent.is_ascii_control());
3321 /// assert!(!space.is_ascii_control());
3322 /// assert!(lf.is_ascii_control());
3323 /// assert!(esc.is_ascii_control());
3325 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3327 pub fn is_ascii_control(&self) -> bool {
3328 if *self >= 0x80 { return false; }
3329 match ASCII_CHARACTER_CLASS[*self as usize] {
3338 uint_impl! { u16, u16, 16, 65535, "", "" }
3343 uint_impl! { u32, u32, 32, 4294967295, "", "" }
3348 uint_impl! { u64, u64, 64, 18446744073709551615, "", "" }
3353 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "#![feature(i128_type)]
3361 #[cfg(target_pointer_width = "16")]
3364 uint_impl! { usize, u16, 16, 65536, "", "" }
3366 #[cfg(target_pointer_width = "32")]
3369 uint_impl! { usize, u32, 32, 4294967295, "", "" }
3372 #[cfg(target_pointer_width = "64")]
3375 uint_impl! { usize, u64, 64, 18446744073709551615, "", "" }
3378 /// A classification of floating point numbers.
3380 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
3381 /// their documentation for more.
3383 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
3384 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
3389 /// use std::num::FpCategory;
3392 /// let num = 12.4_f32;
3393 /// let inf = f32::INFINITY;
3394 /// let zero = 0f32;
3395 /// let sub: f32 = 1.1754942e-38;
3396 /// let nan = f32::NAN;
3398 /// assert_eq!(num.classify(), FpCategory::Normal);
3399 /// assert_eq!(inf.classify(), FpCategory::Infinite);
3400 /// assert_eq!(zero.classify(), FpCategory::Zero);
3401 /// assert_eq!(nan.classify(), FpCategory::Nan);
3402 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
3404 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
3405 #[stable(feature = "rust1", since = "1.0.0")]
3406 pub enum FpCategory {
3407 /// "Not a Number", often obtained by dividing by zero.
3408 #[stable(feature = "rust1", since = "1.0.0")]
3411 /// Positive or negative infinity.
3412 #[stable(feature = "rust1", since = "1.0.0")]
3415 /// Positive or negative zero.
3416 #[stable(feature = "rust1", since = "1.0.0")]
3419 /// De-normalized floating point representation (less precise than `Normal`).
3420 #[stable(feature = "rust1", since = "1.0.0")]
3423 /// A regular floating point number.
3424 #[stable(feature = "rust1", since = "1.0.0")]
3428 /// A built-in floating point number.
3430 #[unstable(feature = "core_float",
3431 reason = "stable interface is via `impl f{32,64}` in later crates",
3433 pub trait Float: Sized {
3434 /// Type used by `to_bits` and `from_bits`.
3435 #[stable(feature = "core_float_bits", since = "1.25.0")]
3438 /// Returns `true` if this value is NaN and false otherwise.
3439 #[stable(feature = "core", since = "1.6.0")]
3440 fn is_nan(self) -> bool;
3441 /// Returns `true` if this value is positive infinity or negative infinity and
3442 /// false otherwise.
3443 #[stable(feature = "core", since = "1.6.0")]
3444 fn is_infinite(self) -> bool;
3445 /// Returns `true` if this number is neither infinite nor NaN.
3446 #[stable(feature = "core", since = "1.6.0")]
3447 fn is_finite(self) -> bool;
3448 /// Returns `true` if this number is neither zero, infinite, denormal, or NaN.
3449 #[stable(feature = "core", since = "1.6.0")]
3450 fn is_normal(self) -> bool;
3451 /// Returns the category that this number falls into.
3452 #[stable(feature = "core", since = "1.6.0")]
3453 fn classify(self) -> FpCategory;
3455 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
3456 /// number is `Float::nan()`.
3457 #[stable(feature = "core", since = "1.6.0")]
3458 fn abs(self) -> Self;
3459 /// Returns a number that represents the sign of `self`.
3461 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
3462 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
3463 /// - `Float::nan()` if the number is `Float::nan()`
3464 #[stable(feature = "core", since = "1.6.0")]
3465 fn signum(self) -> Self;
3467 /// Returns `true` if `self` is positive, including `+0.0` and
3468 /// `Float::infinity()`.
3469 #[stable(feature = "core", since = "1.6.0")]
3470 fn is_sign_positive(self) -> bool;
3471 /// Returns `true` if `self` is negative, including `-0.0` and
3472 /// `Float::neg_infinity()`.
3473 #[stable(feature = "core", since = "1.6.0")]
3474 fn is_sign_negative(self) -> bool;
3476 /// Take the reciprocal (inverse) of a number, `1/x`.
3477 #[stable(feature = "core", since = "1.6.0")]
3478 fn recip(self) -> Self;
3480 /// Raise a number to an integer power.
3482 /// Using this function is generally faster than using `powf`
3483 #[stable(feature = "core", since = "1.6.0")]
3484 fn powi(self, n: i32) -> Self;
3486 /// Convert radians to degrees.
3487 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
3488 fn to_degrees(self) -> Self;
3489 /// Convert degrees to radians.
3490 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
3491 fn to_radians(self) -> Self;
3493 /// Returns the maximum of the two numbers.
3494 #[stable(feature = "core_float_min_max", since="1.20.0")]
3495 fn max(self, other: Self) -> Self;
3496 /// Returns the minimum of the two numbers.
3497 #[stable(feature = "core_float_min_max", since="1.20.0")]
3498 fn min(self, other: Self) -> Self;
3500 /// Raw transmutation to integer.
3501 #[stable(feature = "core_float_bits", since="1.25.0")]
3502 fn to_bits(self) -> Self::Bits;
3503 /// Raw transmutation from integer.
3504 #[stable(feature = "core_float_bits", since="1.25.0")]
3505 fn from_bits(v: Self::Bits) -> Self;
3508 macro_rules! from_str_radix_int_impl {
3510 #[stable(feature = "rust1", since = "1.0.0")]
3511 impl FromStr for $t {
3512 type Err = ParseIntError;
3513 fn from_str(src: &str) -> Result<Self, ParseIntError> {
3514 from_str_radix(src, 10)
3519 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
3521 /// The error type returned when a checked integral type conversion fails.
3522 #[unstable(feature = "try_from", issue = "33417")]
3523 #[derive(Debug, Copy, Clone)]
3524 pub struct TryFromIntError(());
3526 impl TryFromIntError {
3527 #[unstable(feature = "int_error_internals",
3528 reason = "available through Error trait and this method should \
3529 not be exposed publicly",
3532 pub fn __description(&self) -> &str {
3533 "out of range integral type conversion attempted"
3537 #[unstable(feature = "try_from", issue = "33417")]
3538 impl fmt::Display for TryFromIntError {
3539 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3540 self.__description().fmt(fmt)
3544 #[unstable(feature = "try_from", issue = "33417")]
3545 impl From<Infallible> for TryFromIntError {
3546 fn from(infallible: Infallible) -> TryFromIntError {
3552 // no possible bounds violation
3553 macro_rules! try_from_unbounded {
3554 ($source:ty, $($target:ty),*) => {$(
3555 #[unstable(feature = "try_from", issue = "33417")]
3556 impl TryFrom<$source> for $target {
3557 type Error = Infallible;
3560 fn try_from(value: $source) -> Result<Self, Self::Error> {
3561 Ok(value as $target)
3567 // only negative bounds
3568 macro_rules! try_from_lower_bounded {
3569 ($source:ty, $($target:ty),*) => {$(
3570 #[unstable(feature = "try_from", issue = "33417")]
3571 impl TryFrom<$source> for $target {
3572 type Error = TryFromIntError;
3575 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
3579 Err(TryFromIntError(()))
3586 // unsigned to signed (only positive bound)
3587 macro_rules! try_from_upper_bounded {
3588 ($source:ty, $($target:ty),*) => {$(
3589 #[unstable(feature = "try_from", issue = "33417")]
3590 impl TryFrom<$source> for $target {
3591 type Error = TryFromIntError;
3594 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
3595 if u > (<$target>::max_value() as $source) {
3596 Err(TryFromIntError(()))
3606 macro_rules! try_from_both_bounded {
3607 ($source:ty, $($target:ty),*) => {$(
3608 #[unstable(feature = "try_from", issue = "33417")]
3609 impl TryFrom<$source> for $target {
3610 type Error = TryFromIntError;
3613 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
3614 let min = <$target>::min_value() as $source;
3615 let max = <$target>::max_value() as $source;
3616 if u < min || u > max {
3617 Err(TryFromIntError(()))
3627 ($mac:ident, $source:ty, $($target:ty),*) => {$(
3628 $mac!($target, $source);
3632 /// intra-sign conversions
3633 try_from_upper_bounded!(u16, u8);
3634 try_from_upper_bounded!(u32, u16, u8);
3635 try_from_upper_bounded!(u64, u32, u16, u8);
3636 try_from_upper_bounded!(u128, u64, u32, u16, u8);
3638 try_from_both_bounded!(i16, i8);
3639 try_from_both_bounded!(i32, i16, i8);
3640 try_from_both_bounded!(i64, i32, i16, i8);
3641 try_from_both_bounded!(i128, i64, i32, i16, i8);
3643 // unsigned-to-signed
3644 try_from_upper_bounded!(u8, i8);
3645 try_from_upper_bounded!(u16, i8, i16);
3646 try_from_upper_bounded!(u32, i8, i16, i32);
3647 try_from_upper_bounded!(u64, i8, i16, i32, i64);
3648 try_from_upper_bounded!(u128, i8, i16, i32, i64, i128);
3650 // signed-to-unsigned
3651 try_from_lower_bounded!(i8, u8, u16, u32, u64, u128);
3652 try_from_lower_bounded!(i16, u16, u32, u64, u128);
3653 try_from_lower_bounded!(i32, u32, u64, u128);
3654 try_from_lower_bounded!(i64, u64, u128);
3655 try_from_lower_bounded!(i128, u128);
3656 try_from_both_bounded!(i16, u8);
3657 try_from_both_bounded!(i32, u16, u8);
3658 try_from_both_bounded!(i64, u32, u16, u8);
3659 try_from_both_bounded!(i128, u64, u32, u16, u8);
3662 try_from_upper_bounded!(usize, isize);
3663 try_from_lower_bounded!(isize, usize);
3665 #[cfg(target_pointer_width = "16")]
3666 mod ptr_try_from_impls {
3667 use super::TryFromIntError;
3668 use convert::{Infallible, TryFrom};
3670 try_from_upper_bounded!(usize, u8);
3671 try_from_unbounded!(usize, u16, u32, u64, u128);
3672 try_from_upper_bounded!(usize, i8, i16);
3673 try_from_unbounded!(usize, i32, i64, i128);
3675 try_from_both_bounded!(isize, u8);
3676 try_from_lower_bounded!(isize, u16, u32, u64, u128);
3677 try_from_both_bounded!(isize, i8);
3678 try_from_unbounded!(isize, i16, i32, i64, i128);
3680 rev!(try_from_unbounded, usize, u16);
3681 rev!(try_from_upper_bounded, usize, u32, u64, u128);
3682 rev!(try_from_lower_bounded, usize, i8, i16);
3683 rev!(try_from_both_bounded, usize, i32, i64, i128);
3685 rev!(try_from_unbounded, isize, u8);
3686 rev!(try_from_upper_bounded, isize, u16, u32, u64, u128);
3687 rev!(try_from_unbounded, isize, i16);
3688 rev!(try_from_both_bounded, isize, i32, i64, i128);
3691 #[cfg(target_pointer_width = "32")]
3692 mod ptr_try_from_impls {
3693 use super::TryFromIntError;
3694 use convert::{Infallible, TryFrom};
3696 try_from_upper_bounded!(usize, u8, u16);
3697 try_from_unbounded!(usize, u32, u64, u128);
3698 try_from_upper_bounded!(usize, i8, i16, i32);
3699 try_from_unbounded!(usize, i64, i128);
3701 try_from_both_bounded!(isize, u8, u16);
3702 try_from_lower_bounded!(isize, u32, u64, u128);
3703 try_from_both_bounded!(isize, i8, i16);
3704 try_from_unbounded!(isize, i32, i64, i128);
3706 rev!(try_from_unbounded, usize, u16, u32);
3707 rev!(try_from_upper_bounded, usize, u64, u128);
3708 rev!(try_from_lower_bounded, usize, i8, i16, i32);
3709 rev!(try_from_both_bounded, usize, i64, i128);
3711 rev!(try_from_unbounded, isize, u8, u16);
3712 rev!(try_from_upper_bounded, isize, u32, u64, u128);
3713 rev!(try_from_unbounded, isize, i16, i32);
3714 rev!(try_from_both_bounded, isize, i64, i128);
3717 #[cfg(target_pointer_width = "64")]
3718 mod ptr_try_from_impls {
3719 use super::TryFromIntError;
3720 use convert::{Infallible, TryFrom};
3722 try_from_upper_bounded!(usize, u8, u16, u32);
3723 try_from_unbounded!(usize, u64, u128);
3724 try_from_upper_bounded!(usize, i8, i16, i32, i64);
3725 try_from_unbounded!(usize, i128);
3727 try_from_both_bounded!(isize, u8, u16, u32);
3728 try_from_lower_bounded!(isize, u64, u128);
3729 try_from_both_bounded!(isize, i8, i16, i32);
3730 try_from_unbounded!(isize, i64, i128);
3732 rev!(try_from_unbounded, usize, u16, u32, u64);
3733 rev!(try_from_upper_bounded, usize, u128);
3734 rev!(try_from_lower_bounded, usize, i8, i16, i32, i64);
3735 rev!(try_from_both_bounded, usize, i128);
3737 rev!(try_from_unbounded, isize, u8, u16, u32);
3738 rev!(try_from_upper_bounded, isize, u64, u128);
3739 rev!(try_from_unbounded, isize, i16, i32, i64);
3740 rev!(try_from_both_bounded, isize, i128);
3744 trait FromStrRadixHelper: PartialOrd + Copy {
3745 fn min_value() -> Self;
3746 fn max_value() -> Self;
3747 fn from_u32(u: u32) -> Self;
3748 fn checked_mul(&self, other: u32) -> Option<Self>;
3749 fn checked_sub(&self, other: u32) -> Option<Self>;
3750 fn checked_add(&self, other: u32) -> Option<Self>;
3754 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
3756 fn min_value() -> Self { Self::min_value() }
3758 fn max_value() -> Self { Self::max_value() }
3760 fn from_u32(u: u32) -> Self { u as Self }
3762 fn checked_mul(&self, other: u32) -> Option<Self> {
3763 Self::checked_mul(*self, other as Self)
3766 fn checked_sub(&self, other: u32) -> Option<Self> {
3767 Self::checked_sub(*self, other as Self)
3770 fn checked_add(&self, other: u32) -> Option<Self> {
3771 Self::checked_add(*self, other as Self)
3775 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
3777 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
3778 use self::IntErrorKind::*;
3779 use self::ParseIntError as PIE;
3781 assert!(radix >= 2 && radix <= 36,
3782 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
3786 return Err(PIE { kind: Empty });
3789 let is_signed_ty = T::from_u32(0) > T::min_value();
3791 // all valid digits are ascii, so we will just iterate over the utf8 bytes
3792 // and cast them to chars. .to_digit() will safely return None for anything
3793 // other than a valid ascii digit for the given radix, including the first-byte
3794 // of multi-byte sequences
3795 let src = src.as_bytes();
3797 let (is_positive, digits) = match src[0] {
3798 b'+' => (true, &src[1..]),
3799 b'-' if is_signed_ty => (false, &src[1..]),
3803 if digits.is_empty() {
3804 return Err(PIE { kind: Empty });
3807 let mut result = T::from_u32(0);
3809 // The number is positive
3811 let x = match (c as char).to_digit(radix) {
3813 None => return Err(PIE { kind: InvalidDigit }),
3815 result = match result.checked_mul(radix) {
3816 Some(result) => result,
3817 None => return Err(PIE { kind: Overflow }),
3819 result = match result.checked_add(x) {
3820 Some(result) => result,
3821 None => return Err(PIE { kind: Overflow }),
3825 // The number is negative
3827 let x = match (c as char).to_digit(radix) {
3829 None => return Err(PIE { kind: InvalidDigit }),
3831 result = match result.checked_mul(radix) {
3832 Some(result) => result,
3833 None => return Err(PIE { kind: Underflow }),
3835 result = match result.checked_sub(x) {
3836 Some(result) => result,
3837 None => return Err(PIE { kind: Underflow }),
3844 /// An error which can be returned when parsing an integer.
3846 /// This error is used as the error type for the `from_str_radix()` functions
3847 /// on the primitive integer types, such as [`i8::from_str_radix`].
3849 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
3850 #[derive(Debug, Clone, PartialEq, Eq)]
3851 #[stable(feature = "rust1", since = "1.0.0")]
3852 pub struct ParseIntError {
3856 #[derive(Debug, Clone, PartialEq, Eq)]
3864 impl ParseIntError {
3865 #[unstable(feature = "int_error_internals",
3866 reason = "available through Error trait and this method should \
3867 not be exposed publicly",
3870 pub fn __description(&self) -> &str {
3872 IntErrorKind::Empty => "cannot parse integer from empty string",
3873 IntErrorKind::InvalidDigit => "invalid digit found in string",
3874 IntErrorKind::Overflow => "number too large to fit in target type",
3875 IntErrorKind::Underflow => "number too small to fit in target type",
3880 #[stable(feature = "rust1", since = "1.0.0")]
3881 impl fmt::Display for ParseIntError {
3882 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3883 self.__description().fmt(f)
3887 #[stable(feature = "rust1", since = "1.0.0")]
3888 pub use num::dec2flt::ParseFloatError;
3890 // Conversion traits for primitive integer and float types
3891 // Conversions T -> T are covered by a blanket impl and therefore excluded
3892 // Some conversions from and to usize/isize are not implemented due to portability concerns
3893 macro_rules! impl_from {
3894 ($Small: ty, $Large: ty, #[$attr:meta]) => {
3896 impl From<$Small> for $Large {
3898 fn from(small: $Small) -> $Large {
3905 // Unsigned -> Unsigned
3906 impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3907 impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3908 impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3909 impl_from! { u8, u128, #[unstable(feature = "i128", issue = "35118")] }
3910 impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3911 impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3912 impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3913 impl_from! { u16, u128, #[unstable(feature = "i128", issue = "35118")] }
3914 impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3915 impl_from! { u32, u128, #[unstable(feature = "i128", issue = "35118")] }
3916 impl_from! { u64, u128, #[unstable(feature = "i128", issue = "35118")] }
3919 impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3920 impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3921 impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3922 impl_from! { i8, i128, #[unstable(feature = "i128", issue = "35118")] }
3923 impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3924 impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3925 impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3926 impl_from! { i16, i128, #[unstable(feature = "i128", issue = "35118")] }
3927 impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3928 impl_from! { i32, i128, #[unstable(feature = "i128", issue = "35118")] }
3929 impl_from! { i64, i128, #[unstable(feature = "i128", issue = "35118")] }
3931 // Unsigned -> Signed
3932 impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3933 impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3934 impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3935 impl_from! { u8, i128, #[unstable(feature = "i128", issue = "35118")] }
3936 impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3937 impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3938 impl_from! { u16, i128, #[unstable(feature = "i128", issue = "35118")] }
3939 impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3940 impl_from! { u32, i128, #[unstable(feature = "i128", issue = "35118")] }
3941 impl_from! { u64, i128, #[unstable(feature = "i128", issue = "35118")] }
3943 // Note: integers can only be represented with full precision in a float if
3944 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
3945 // Lossy float conversions are not implemented at this time.
3948 impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3949 impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3950 impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3951 impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3952 impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3954 // Unsigned -> Float
3955 impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3956 impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3957 impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3958 impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3959 impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3962 impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3964 static ASCII_LOWERCASE_MAP: [u8; 256] = [
3965 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
3966 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
3967 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
3968 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
3969 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
3970 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
3971 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
3972 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
3975 b'a', b'b', b'c', b'd', b'e', b'f', b'g',
3976 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
3977 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
3980 b'[', b'\\', b']', b'^', b'_',
3981 b'`', b'a', b'b', b'c', b'd', b'e', b'f', b'g',
3982 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
3983 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
3984 b'x', b'y', b'z', b'{', b'|', b'}', b'~', 0x7f,
3985 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
3986 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
3987 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
3988 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
3989 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
3990 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
3991 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
3992 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
3993 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
3994 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
3995 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
3996 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
3997 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
3998 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
3999 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4000 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4003 static ASCII_UPPERCASE_MAP: [u8; 256] = [
4004 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4005 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4006 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4007 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4008 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4009 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4010 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4011 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4012 b'@', b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4013 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4014 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4015 b'X', b'Y', b'Z', b'[', b'\\', b']', b'^', b'_',
4018 b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4019 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4020 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4023 b'{', b'|', b'}', b'~', 0x7f,
4024 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4025 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4026 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4027 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4028 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4029 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4030 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4031 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4032 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4033 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4034 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4035 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4036 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4037 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4038 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4039 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4042 enum AsciiCharacterClass {
4044 Cw, // control whitespace
4048 Lx, // lowercase hex digit
4050 Ux, // uppercase hex digit
4053 use self::AsciiCharacterClass::*;
4055 static ASCII_CHARACTER_CLASS: [AsciiCharacterClass; 128] = [
4056 // _0 _1 _2 _3 _4 _5 _6 _7 _8 _9 _a _b _c _d _e _f
4057 C, C, C, C, C, C, C, C, C, Cw,Cw,C, Cw,Cw,C, C, // 0_
4058 C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, // 1_
4059 W, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, // 2_
4060 D, D, D, D, D, D, D, D, D, D, P, P, P, P, P, P, // 3_
4061 P, Ux,Ux,Ux,Ux,Ux,Ux,U, U, U, U, U, U, U, U, U, // 4_
4062 U, U, U, U, U, U, U, U, U, U, U, P, P, P, P, P, // 5_
4063 P, Lx,Lx,Lx,Lx,Lx,Lx,L, L, L, L, L, L, L, L, L, // 6_
4064 L, L, L, L, L, L, L, L, L, L, L, P, P, P, P, C, // 7_