1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Numeric traits and functions for the built-in numeric types.
13 #![stable(feature = "rust1", since = "1.0.0")]
23 macro_rules! impl_nonzero_fmt {
24 ( ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
26 #[stable(feature = "nonzero", since = "1.28.0")]
27 impl fmt::$Trait for $Ty {
29 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
37 macro_rules! doc_comment {
38 ($x:expr, $($tt:tt)*) => {
44 macro_rules! nonzero_integers {
45 ( $( $Ty: ident($Int: ty); )+ ) => {
48 concat!("An integer that is known not to equal zero.
50 This enables some memory layout optimization.
51 For example, `Option<", stringify!($Ty), ">` is the same size as `", stringify!($Int), "`:
54 use std::mem::size_of;
55 assert_eq!(size_of::<Option<std::num::", stringify!($Ty), ">>(), size_of::<", stringify!($Int),
58 #[stable(feature = "nonzero", since = "1.28.0")]
59 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
61 pub struct $Ty(NonZero<$Int>);
65 /// Create a non-zero without checking the value.
69 /// The value must not be zero.
70 #[stable(feature = "nonzero", since = "1.28.0")]
72 pub const unsafe fn new_unchecked(n: $Int) -> Self {
76 /// Create a non-zero if the given value is not zero.
77 #[stable(feature = "nonzero", since = "1.28.0")]
79 pub fn new(n: $Int) -> Option<Self> {
87 /// Returns the value as a primitive type.
88 #[stable(feature = "nonzero", since = "1.28.0")]
90 pub fn get(self) -> $Int {
96 #[stable(feature = "nonzero", since = "1.28.0")]
97 impl From<$Ty> for $Int {
98 fn from(nonzero: $Ty) -> Self {
104 (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
119 /// Provides intentionally-wrapped arithmetic on `T`.
121 /// Operations like `+` on `u32` values is intended to never overflow,
122 /// and in some debug configurations overflow is detected and results
123 /// in a panic. While most arithmetic falls into this category, some
124 /// code explicitly expects and relies upon modular arithmetic (e.g.,
127 /// Wrapping arithmetic can be achieved either through methods like
128 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
129 /// all standard arithmetic operations on the underlying value are
130 /// intended to have wrapping semantics.
132 /// The underlying value can be retrieved through the `.0` index of the
133 /// `Wrapping` tuple.
138 /// use std::num::Wrapping;
140 /// let zero = Wrapping(0u32);
141 /// let one = Wrapping(1u32);
143 /// assert_eq!(std::u32::MAX, (zero - one).0);
145 #[stable(feature = "rust1", since = "1.0.0")]
146 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
148 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")]
151 #[stable(feature = "rust1", since = "1.0.0")]
152 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
153 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
158 #[stable(feature = "wrapping_display", since = "1.10.0")]
159 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
160 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
165 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
166 impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
167 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
172 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
173 impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
174 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
179 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
180 impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
181 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
186 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
187 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
188 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
193 // All these modules are technically private and only exposed for coretests:
201 // `Int` + `SignedInt` implemented for signed integers
202 macro_rules! int_impl {
203 ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $Min:expr, $Max:expr, $Feature:expr,
204 $EndFeature:expr, $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
205 $reversed:expr, $le_bytes:expr, $be_bytes:expr) => {
207 concat!("Returns the smallest value that can be represented by this integer type.
214 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), ", stringify!($Min), ");",
217 #[stable(feature = "rust1", since = "1.0.0")]
219 pub const fn min_value() -> Self {
220 !0 ^ ((!0 as $UnsignedT) >> 1) as Self
225 concat!("Returns the largest value that can be represented by this integer type.
232 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ", stringify!($Max), ");",
235 #[stable(feature = "rust1", since = "1.0.0")]
237 pub const fn max_value() -> Self {
243 concat!("Converts a string slice in a given base to an integer.
245 The string is expected to be an optional `+` or `-` sign followed by digits.
246 Leading and trailing whitespace represent an error. Digits are a subset of these characters,
247 depending on `radix`:
255 This function panics if `radix` is not in the range from 2 to 36.
262 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
265 #[stable(feature = "rust1", since = "1.0.0")]
266 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
267 from_str_radix(src, radix)
272 concat!("Returns the number of ones in the binary representation of `self`.
279 ", $Feature, "let n = 0b100_0000", stringify!($SelfT), ";
281 assert_eq!(n.count_ones(), 1);",
285 #[stable(feature = "rust1", since = "1.0.0")]
286 #[rustc_const_unstable(feature = "const_int_ops")]
288 pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
292 concat!("Returns the number of zeros in the binary representation of `self`.
299 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 1);", $EndFeature, "
301 #[stable(feature = "rust1", since = "1.0.0")]
302 #[rustc_const_unstable(feature = "const_int_ops")]
304 pub const fn count_zeros(self) -> u32 {
310 concat!("Returns the number of leading zeros in the binary representation of `self`.
317 ", $Feature, "let n = -1", stringify!($SelfT), ";
319 assert_eq!(n.leading_zeros(), 0);",
322 #[stable(feature = "rust1", since = "1.0.0")]
323 #[rustc_const_unstable(feature = "const_int_ops")]
325 pub const fn leading_zeros(self) -> u32 {
326 (self as $UnsignedT).leading_zeros()
331 concat!("Returns the number of trailing zeros in the binary representation of `self`.
338 ", $Feature, "let n = -4", stringify!($SelfT), ";
340 assert_eq!(n.trailing_zeros(), 2);",
343 #[stable(feature = "rust1", since = "1.0.0")]
344 #[rustc_const_unstable(feature = "const_int_ops")]
346 pub const fn trailing_zeros(self) -> u32 {
347 (self as $UnsignedT).trailing_zeros()
352 #[stable(feature = "rust1", since = "1.0.0")]
355 pub fn rotate_left(self, n: u32) -> Self {
356 (self as $UnsignedT).rotate_left(n) as Self
360 concat!("Shifts the bits to the left by a specified amount, `n`,
361 wrapping the truncated bits to the end of the resulting integer.
363 Please note this isn't the same operation as `<<`!
370 let n = ", $rot_op, stringify!($SelfT), ";
371 let m = ", $rot_result, ";
373 assert_eq!(n.rotate_left(", $rot, "), m);
375 #[stable(feature = "rust1", since = "1.0.0")]
376 #[rustc_const_unstable(feature = "const_int_rotate")]
379 pub const fn rotate_left(self, n: u32) -> Self {
380 (self as $UnsignedT).rotate_left(n) as Self
385 #[stable(feature = "rust1", since = "1.0.0")]
388 pub fn rotate_right(self, n: u32) -> Self {
389 (self as $UnsignedT).rotate_right(n) as Self
393 concat!("Shifts the bits to the right by a specified amount, `n`,
394 wrapping the truncated bits to the beginning of the resulting
397 Please note this isn't the same operation as `>>`!
404 let n = ", $rot_result, stringify!($SelfT), ";
405 let m = ", $rot_op, ";
407 assert_eq!(n.rotate_right(", $rot, "), m);
409 #[stable(feature = "rust1", since = "1.0.0")]
410 #[rustc_const_unstable(feature = "const_int_rotate")]
413 pub const fn rotate_right(self, n: u32) -> Self {
414 (self as $UnsignedT).rotate_right(n) as Self
419 concat!("Reverses the byte order of the integer.
426 let n = ", $swap_op, stringify!($SelfT), ";
428 let m = n.swap_bytes();
430 assert_eq!(m, ", $swapped, ");
432 #[stable(feature = "rust1", since = "1.0.0")]
433 #[rustc_const_unstable(feature = "const_int_ops")]
435 pub const fn swap_bytes(self) -> Self {
436 (self as $UnsignedT).swap_bytes() as Self
441 #[unstable(feature = "reverse_bits", issue = "48763")]
444 pub fn reverse_bits(self) -> Self {
445 (self as $UnsignedT).reverse_bits() as Self
449 concat!("Reverses the bit pattern of the integer.
456 #![feature(reverse_bits)]
458 let n = ", $swap_op, stringify!($SelfT), ";
459 let m = n.reverse_bits();
461 assert_eq!(m, ", $reversed, ");
463 #[unstable(feature = "reverse_bits", issue = "48763")]
464 #[rustc_const_unstable(feature = "const_int_conversion")]
467 pub const fn reverse_bits(self) -> Self {
468 (self as $UnsignedT).reverse_bits() as Self
473 concat!("Converts an integer from big endian to the target's endianness.
475 On big endian this is a no-op. On little endian the bytes are swapped.
482 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
484 if cfg!(target_endian = \"big\") {
485 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
487 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
491 #[stable(feature = "rust1", since = "1.0.0")]
492 #[rustc_const_unstable(feature = "const_int_ops")]
494 pub const fn from_be(x: Self) -> Self {
495 #[cfg(target_endian = "big")]
499 #[cfg(not(target_endian = "big"))]
507 concat!("Converts an integer from little endian to the target's endianness.
509 On little endian this is a no-op. On big endian the bytes are swapped.
516 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
518 if cfg!(target_endian = \"little\") {
519 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
521 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
525 #[stable(feature = "rust1", since = "1.0.0")]
526 #[rustc_const_unstable(feature = "const_int_ops")]
528 pub const fn from_le(x: Self) -> Self {
529 #[cfg(target_endian = "little")]
533 #[cfg(not(target_endian = "little"))]
541 concat!("Converts `self` to big endian from the target's endianness.
543 On big endian this is a no-op. On little endian the bytes are swapped.
550 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
552 if cfg!(target_endian = \"big\") {
553 assert_eq!(n.to_be(), n)
555 assert_eq!(n.to_be(), n.swap_bytes())
559 #[stable(feature = "rust1", since = "1.0.0")]
560 #[rustc_const_unstable(feature = "const_int_ops")]
562 pub const fn to_be(self) -> Self { // or not to be?
563 #[cfg(target_endian = "big")]
567 #[cfg(not(target_endian = "big"))]
575 concat!("Converts `self` to little endian from the target's endianness.
577 On little endian this is a no-op. On big endian the bytes are swapped.
584 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
586 if cfg!(target_endian = \"little\") {
587 assert_eq!(n.to_le(), n)
589 assert_eq!(n.to_le(), n.swap_bytes())
593 #[stable(feature = "rust1", since = "1.0.0")]
594 #[rustc_const_unstable(feature = "const_int_ops")]
596 pub const fn to_le(self) -> Self {
597 #[cfg(target_endian = "little")]
601 #[cfg(not(target_endian = "little"))]
609 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
610 if overflow occurred.
617 ", $Feature, "assert_eq!((", stringify!($SelfT),
618 "::max_value() - 2).checked_add(1), Some(", stringify!($SelfT), "::max_value() - 1));
619 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);",
622 #[stable(feature = "rust1", since = "1.0.0")]
624 pub fn checked_add(self, rhs: Self) -> Option<Self> {
625 let (a, b) = self.overflowing_add(rhs);
626 if b {None} else {Some(a)}
631 concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
639 ", $Feature, "assert_eq!((", stringify!($SelfT),
640 "::min_value() + 2).checked_sub(1), Some(", stringify!($SelfT), "::min_value() + 1));
641 assert_eq!((", stringify!($SelfT), "::min_value() + 2).checked_sub(3), None);",
644 #[stable(feature = "rust1", since = "1.0.0")]
646 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
647 let (a, b) = self.overflowing_sub(rhs);
648 if b {None} else {Some(a)}
653 concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
661 ", $Feature, "assert_eq!(", stringify!($SelfT),
662 "::max_value().checked_mul(1), Some(", stringify!($SelfT), "::max_value()));
663 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);",
666 #[stable(feature = "rust1", since = "1.0.0")]
668 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
669 let (a, b) = self.overflowing_mul(rhs);
670 if b {None} else {Some(a)}
675 concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
676 or the division results in overflow.
683 ", $Feature, "assert_eq!((", stringify!($SelfT),
684 "::min_value() + 1).checked_div(-1), Some(", stringify!($Max), "));
685 assert_eq!(", stringify!($SelfT), "::min_value().checked_div(-1), None);
686 assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
689 #[stable(feature = "rust1", since = "1.0.0")]
691 pub fn checked_div(self, rhs: Self) -> Option<Self> {
692 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
695 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
701 concat!("Checked Euclidean division. Computes `self.div_euc(rhs)`,
702 returning `None` if `rhs == 0` or the division results in overflow.
709 #![feature(euclidean_division)]
710 assert_eq!((", stringify!($SelfT),
711 "::min_value() + 1).checked_div_euc(-1), Some(", stringify!($Max), "));
712 assert_eq!(", stringify!($SelfT), "::min_value().checked_div_euc(-1), None);
713 assert_eq!((1", stringify!($SelfT), ").checked_div_euc(0), None);
715 #[unstable(feature = "euclidean_division", issue = "49048")]
717 pub fn checked_div_euc(self, rhs: Self) -> Option<Self> {
718 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
721 Some(self.div_euc(rhs))
727 concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
728 `rhs == 0` or the division results in overflow.
735 ", $Feature, "use std::", stringify!($SelfT), ";
737 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
738 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
739 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
742 #[stable(feature = "wrapping", since = "1.7.0")]
744 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
745 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
748 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
754 concat!("Checked Euclidean modulo. Computes `self.mod_euc(rhs)`, returning `None` if
755 `rhs == 0` or the division results in overflow.
762 #![feature(euclidean_division)]
763 use std::", stringify!($SelfT), ";
765 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(2), Some(1));
766 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(0), None);
767 assert_eq!(", stringify!($SelfT), "::MIN.checked_mod_euc(-1), None);
769 #[unstable(feature = "euclidean_division", issue = "49048")]
771 pub fn checked_mod_euc(self, rhs: Self) -> Option<Self> {
772 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
775 Some(self.mod_euc(rhs))
781 concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
788 ", $Feature, "use std::", stringify!($SelfT), ";
790 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
791 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
794 #[stable(feature = "wrapping", since = "1.7.0")]
796 pub fn checked_neg(self) -> Option<Self> {
797 let (a, b) = self.overflowing_neg();
798 if b {None} else {Some(a)}
803 concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
804 than or equal to the number of bits in `self`.
811 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
812 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
815 #[stable(feature = "wrapping", since = "1.7.0")]
817 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
818 let (a, b) = self.overflowing_shl(rhs);
819 if b {None} else {Some(a)}
824 concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
825 larger than or equal to the number of bits in `self`.
832 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
833 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
836 #[stable(feature = "wrapping", since = "1.7.0")]
838 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
839 let (a, b) = self.overflowing_shr(rhs);
840 if b {None} else {Some(a)}
845 concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
853 ", $Feature, "use std::", stringify!($SelfT), ";
855 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
856 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
859 #[stable(feature = "no_panic_abs", since = "1.13.0")]
861 pub fn checked_abs(self) -> Option<Self> {
862 if self.is_negative() {
871 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
879 #![feature(no_panic_pow)]
880 ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
881 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);",
885 #[unstable(feature = "no_panic_pow", issue = "48320")]
887 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
889 let mut acc: Self = 1;
893 acc = acc.checked_mul(base)?;
896 base = base.checked_mul(base)?;
899 // Deal with the final bit of the exponent separately, since
900 // squaring the base afterwards is not necessary and may cause a
901 // needless overflow.
903 acc = acc.checked_mul(base)?;
911 concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
912 bounds instead of overflowing.
919 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
920 assert_eq!(", stringify!($SelfT), "::max_value().saturating_add(100), ", stringify!($SelfT),
924 #[stable(feature = "rust1", since = "1.0.0")]
926 pub fn saturating_add(self, rhs: Self) -> Self {
927 match self.checked_add(rhs) {
929 None if rhs >= 0 => Self::max_value(),
930 None => Self::min_value(),
936 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
937 numeric bounds instead of overflowing.
944 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
945 assert_eq!(", stringify!($SelfT), "::min_value().saturating_sub(100), ", stringify!($SelfT),
949 #[stable(feature = "rust1", since = "1.0.0")]
951 pub fn saturating_sub(self, rhs: Self) -> Self {
952 match self.checked_sub(rhs) {
954 None if rhs >= 0 => Self::min_value(),
955 None => Self::max_value(),
961 concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
962 numeric bounds instead of overflowing.
969 ", $Feature, "use std::", stringify!($SelfT), ";
971 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
972 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
973 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
976 #[stable(feature = "wrapping", since = "1.7.0")]
978 pub fn saturating_mul(self, rhs: Self) -> Self {
979 self.checked_mul(rhs).unwrap_or_else(|| {
980 if (self < 0 && rhs < 0) || (self > 0 && rhs > 0) {
990 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
991 saturating at the numeric bounds instead of overflowing.
998 #![feature(no_panic_pow)]
999 ", $Feature, "use std::", stringify!($SelfT), ";
1001 assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
1002 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
1003 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
1006 #[unstable(feature = "no_panic_pow", issue = "48320")]
1008 pub fn saturating_pow(self, exp: u32) -> Self {
1009 match self.checked_pow(exp) {
1011 None if self < 0 && exp % 2 == 1 => Self::min_value(),
1012 None => Self::max_value(),
1018 #[stable(feature = "rust1", since = "1.0.0")]
1021 pub fn wrapping_add(self, rhs: Self) -> Self {
1023 intrinsics::overflowing_add(self, rhs)
1028 concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
1029 boundary of the type.
1036 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
1037 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_add(2), ", stringify!($SelfT),
1038 "::min_value() + 1);",
1041 #[stable(feature = "rust1", since = "1.0.0")]
1042 #[rustc_const_unstable(feature = "const_int_wrapping")]
1045 pub const fn wrapping_add(self, rhs: Self) -> Self {
1047 intrinsics::overflowing_add(self, rhs)
1053 #[stable(feature = "rust1", since = "1.0.0")]
1056 pub fn wrapping_sub(self, rhs: Self) -> Self {
1058 intrinsics::overflowing_sub(self, rhs)
1063 concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1064 boundary of the type.
1071 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
1072 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::max_value()), ",
1073 stringify!($SelfT), "::max_value());",
1076 #[stable(feature = "rust1", since = "1.0.0")]
1077 #[rustc_const_unstable(feature = "const_int_wrapping")]
1080 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1082 intrinsics::overflowing_sub(self, rhs)
1088 #[stable(feature = "rust1", since = "1.0.0")]
1091 pub fn wrapping_mul(self, rhs: Self) -> Self {
1093 intrinsics::overflowing_mul(self, rhs)
1098 concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1099 the boundary of the type.
1106 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
1107 assert_eq!(11i8.wrapping_mul(12), -124);",
1110 #[stable(feature = "rust1", since = "1.0.0")]
1111 #[rustc_const_unstable(feature = "const_int_wrapping")]
1114 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1116 intrinsics::overflowing_mul(self, rhs)
1122 concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1123 boundary of the type.
1125 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1126 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1127 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1131 This function will panic if `rhs` is 0.
1138 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
1139 assert_eq!((-128i8).wrapping_div(-1), -128);",
1142 #[stable(feature = "num_wrapping", since = "1.2.0")]
1144 pub fn wrapping_div(self, rhs: Self) -> Self {
1145 self.overflowing_div(rhs).0
1150 concat!("Wrapping Euclidean division. Computes `self.div_euc(rhs)`,
1151 wrapping around at the boundary of the type.
1153 Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1154 for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1155 type. In this case, this method returns `MIN` itself.
1159 This function will panic if `rhs` is 0.
1166 #![feature(euclidean_division)]
1167 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euc(10), 10);
1168 assert_eq!((-128i8).wrapping_div_euc(-1), -128);
1170 #[unstable(feature = "euclidean_division", issue = "49048")]
1172 pub fn wrapping_div_euc(self, rhs: Self) -> Self {
1173 self.overflowing_div_euc(rhs).0
1178 concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1179 boundary of the type.
1181 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1182 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1183 this function returns `0`.
1187 This function will panic if `rhs` is 0.
1194 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
1195 assert_eq!((-128i8).wrapping_rem(-1), 0);",
1198 #[stable(feature = "num_wrapping", since = "1.2.0")]
1200 pub fn wrapping_rem(self, rhs: Self) -> Self {
1201 self.overflowing_rem(rhs).0
1206 concat!("Wrapping Euclidean modulo. Computes `self.mod_euc(rhs)`, wrapping around at the
1207 boundary of the type.
1209 Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1210 for the type). In this case, this method returns 0.
1214 This function will panic if `rhs` is 0.
1221 #![feature(euclidean_division)]
1222 assert_eq!(100", stringify!($SelfT), ".wrapping_mod_euc(10), 0);
1223 assert_eq!((-128i8).wrapping_mod_euc(-1), 0);
1225 #[unstable(feature = "euclidean_division", issue = "49048")]
1227 pub fn wrapping_mod_euc(self, rhs: Self) -> Self {
1228 self.overflowing_mod_euc(rhs).0
1233 concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1236 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1237 is the negative minimal value for the type); this is a positive value that is too large to represent
1238 in the type. In such a case, this function returns `MIN` itself.
1245 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
1246 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_neg(), ", stringify!($SelfT),
1250 #[stable(feature = "num_wrapping", since = "1.2.0")]
1252 pub fn wrapping_neg(self) -> Self {
1253 self.overflowing_neg().0
1258 #[stable(feature = "num_wrapping", since = "1.2.0")]
1261 pub fn wrapping_shl(self, rhs: u32) -> Self {
1263 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1268 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1269 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1271 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1272 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1273 The primitive integer types all implement a `rotate_left` function, which may be what you want
1281 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
1282 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
1285 #[stable(feature = "num_wrapping", since = "1.2.0")]
1286 #[rustc_const_unstable(feature = "const_int_wrapping")]
1289 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1291 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1297 #[stable(feature = "num_wrapping", since = "1.2.0")]
1300 pub fn wrapping_shr(self, rhs: u32) -> Self {
1302 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1307 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1308 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1310 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1311 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1312 end. The primitive integer types all implement a `rotate_right` function, which may be what you want
1320 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
1321 assert_eq!((-128i16).wrapping_shr(64), -128);",
1324 #[stable(feature = "num_wrapping", since = "1.2.0")]
1325 #[rustc_const_unstable(feature = "const_int_wrapping")]
1328 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1330 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1336 concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1337 the boundary of the type.
1339 The only case where such wrapping can occur is when one takes the absolute value of the negative
1340 minimal value for the type this is a positive value that is too large to represent in the type. In
1341 such a case, this function returns `MIN` itself.
1348 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
1349 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
1350 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_abs(), ", stringify!($SelfT),
1352 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1355 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1357 pub fn wrapping_abs(self) -> Self {
1358 if self.is_negative() {
1367 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1368 wrapping around at the boundary of the type.
1375 #![feature(no_panic_pow)]
1376 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);
1377 assert_eq!(3i8.wrapping_pow(5), -13);
1378 assert_eq!(3i8.wrapping_pow(6), -39);",
1381 #[unstable(feature = "no_panic_pow", issue = "48320")]
1383 pub fn wrapping_pow(self, mut exp: u32) -> Self {
1384 let mut base = self;
1385 let mut acc: Self = 1;
1389 acc = acc.wrapping_mul(base);
1392 base = base.wrapping_mul(base);
1395 // Deal with the final bit of the exponent separately, since
1396 // squaring the base afterwards is not necessary and may cause a
1397 // needless overflow.
1399 acc = acc.wrapping_mul(base);
1407 #[stable(feature = "wrapping", since = "1.7.0")]
1410 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1411 let (a, b) = unsafe {
1412 intrinsics::add_with_overflow(self as $ActualT,
1419 concat!("Calculates `self` + `rhs`
1421 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1422 occur. If an overflow would have occurred then the wrapped value is returned.
1429 ", $Feature, "use std::", stringify!($SelfT), ";
1431 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1432 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
1433 "::MIN, true));", $EndFeature, "
1435 #[stable(feature = "wrapping", since = "1.7.0")]
1436 #[rustc_const_unstable(feature = "const_int_overflowing")]
1439 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1440 let (a, b) = unsafe {
1441 intrinsics::add_with_overflow(self as $ActualT,
1449 #[stable(feature = "wrapping", since = "1.7.0")]
1452 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1453 let (a, b) = unsafe {
1454 intrinsics::sub_with_overflow(self as $ActualT,
1461 concat!("Calculates `self` - `rhs`
1463 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1464 would occur. If an overflow would have occurred then the wrapped value is returned.
1471 ", $Feature, "use std::", stringify!($SelfT), ";
1473 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
1474 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
1475 "::MAX, true));", $EndFeature, "
1477 #[stable(feature = "wrapping", since = "1.7.0")]
1478 #[rustc_const_unstable(feature = "const_int_overflowing")]
1481 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1482 let (a, b) = unsafe {
1483 intrinsics::sub_with_overflow(self as $ActualT,
1491 #[stable(feature = "wrapping", since = "1.7.0")]
1494 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1495 let (a, b) = unsafe {
1496 intrinsics::mul_with_overflow(self as $ActualT,
1503 concat!("Calculates the multiplication of `self` and `rhs`.
1505 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1506 would occur. If an overflow would have occurred then the wrapped value is returned.
1513 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1514 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1517 #[stable(feature = "wrapping", since = "1.7.0")]
1518 #[rustc_const_unstable(feature = "const_int_overflowing")]
1521 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1522 let (a, b) = unsafe {
1523 intrinsics::mul_with_overflow(self as $ActualT,
1531 concat!("Calculates the divisor when `self` is divided by `rhs`.
1533 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1534 occur. If an overflow would occur then self is returned.
1538 This function will panic if `rhs` is 0.
1545 ", $Feature, "use std::", stringify!($SelfT), ";
1547 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1548 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1553 #[stable(feature = "wrapping", since = "1.7.0")]
1554 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1555 if self == Self::min_value() && rhs == -1 {
1564 concat!("Calculates the quotient of Euclidean division `self.div_euc(rhs)`.
1566 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1567 occur. If an overflow would occur then `self` is returned.
1571 This function will panic if `rhs` is 0.
1578 #![feature(euclidean_division)]
1579 use std::", stringify!($SelfT), ";
1581 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euc(2), (2, false));
1582 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euc(-1), (", stringify!($SelfT),
1586 #[unstable(feature = "euclidean_division", issue = "49048")]
1587 pub fn overflowing_div_euc(self, rhs: Self) -> (Self, bool) {
1588 if self == Self::min_value() && rhs == -1 {
1591 (self.div_euc(rhs), false)
1597 concat!("Calculates the remainder when `self` is divided by `rhs`.
1599 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1600 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1604 This function will panic if `rhs` is 0.
1611 ", $Feature, "use std::", stringify!($SelfT), ";
1613 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1614 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1618 #[stable(feature = "wrapping", since = "1.7.0")]
1619 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1620 if self == Self::min_value() && rhs == -1 {
1630 concat!("Calculates the remainder `self.mod_euc(rhs)` by Euclidean division.
1632 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1633 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1637 This function will panic if `rhs` is 0.
1644 #![feature(euclidean_division)]
1645 use std::", stringify!($SelfT), ";
1647 assert_eq!(5", stringify!($SelfT), ".overflowing_mod_euc(2), (1, false));
1648 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_mod_euc(-1), (0, true));
1650 #[unstable(feature = "euclidean_division", issue = "49048")]
1652 pub fn overflowing_mod_euc(self, rhs: Self) -> (Self, bool) {
1653 if self == Self::min_value() && rhs == -1 {
1656 (self.mod_euc(rhs), false)
1663 concat!("Negates self, overflowing if this is equal to the minimum value.
1665 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1666 happened. If `self` is the minimum value (e.g. `i32::MIN` for values of type `i32`), then the
1667 minimum value will be returned again and `true` will be returned for an overflow happening.
1674 ", $Feature, "use std::", stringify!($SelfT), ";
1676 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1677 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1678 "::MIN, true));", $EndFeature, "
1681 #[stable(feature = "wrapping", since = "1.7.0")]
1682 pub fn overflowing_neg(self) -> (Self, bool) {
1683 if self == Self::min_value() {
1684 (Self::min_value(), true)
1692 #[stable(feature = "wrapping", since = "1.7.0")]
1695 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1696 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1700 concat!("Shifts self left by `rhs` bits.
1702 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1703 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1704 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1711 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1712 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1715 #[stable(feature = "wrapping", since = "1.7.0")]
1716 #[rustc_const_unstable(feature = "const_int_overflowing")]
1719 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1720 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1725 #[stable(feature = "wrapping", since = "1.7.0")]
1728 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1729 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1733 concat!("Shifts self right by `rhs` bits.
1735 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1736 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1737 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1744 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1745 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1748 #[stable(feature = "wrapping", since = "1.7.0")]
1749 #[rustc_const_unstable(feature = "const_int_overflowing")]
1752 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1753 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1758 concat!("Computes the absolute value of `self`.
1760 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1761 happened. If self is the minimum value (e.g. ", stringify!($SelfT), "::MIN for values of type
1762 ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1763 for an overflow happening.
1770 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1771 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1772 assert_eq!((", stringify!($SelfT), "::min_value()).overflowing_abs(), (", stringify!($SelfT),
1773 "::min_value(), true));",
1776 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1778 pub fn overflowing_abs(self) -> (Self, bool) {
1779 if self.is_negative() {
1780 self.overflowing_neg()
1788 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1790 Returns a tuple of the exponentiation along with a bool indicating
1791 whether an overflow happened.
1798 #![feature(no_panic_pow)]
1799 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));
1800 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
1803 #[unstable(feature = "no_panic_pow", issue = "48320")]
1805 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1806 let mut base = self;
1807 let mut acc: Self = 1;
1808 let mut overflown = false;
1809 // Scratch space for storing results of overflowing_mul.
1814 r = acc.overflowing_mul(base);
1819 r = base.overflowing_mul(base);
1824 // Deal with the final bit of the exponent separately, since
1825 // squaring the base afterwards is not necessary and may cause a
1826 // needless overflow.
1828 r = acc.overflowing_mul(base);
1838 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1845 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
1847 assert_eq!(x.pow(5), 32);",
1850 #[stable(feature = "rust1", since = "1.0.0")]
1852 #[rustc_inherit_overflow_checks]
1853 pub fn pow(self, mut exp: u32) -> Self {
1854 let mut base = self;
1865 // Deal with the final bit of the exponent separately, since
1866 // squaring the base afterwards is not necessary and may cause a
1867 // needless overflow.
1877 concat!("Calculates the quotient of Euclidean division of `self` by `rhs`.
1879 This computes the integer `n` such that `self = n * rhs + self.mod_euc(rhs)`.
1880 In other words, the result is `self / rhs` rounded to the integer `n`
1881 such that `self >= n * rhs`.
1885 This function will panic if `rhs` is 0.
1892 #![feature(euclidean_division)]
1893 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1896 assert_eq!(a.div_euc(b), 1); // 7 >= 4 * 1
1897 assert_eq!(a.div_euc(-b), -1); // 7 >= -4 * -1
1898 assert_eq!((-a).div_euc(b), -2); // -7 >= 4 * -2
1899 assert_eq!((-a).div_euc(-b), 2); // -7 >= -4 * 2
1901 #[unstable(feature = "euclidean_division", issue = "49048")]
1903 #[rustc_inherit_overflow_checks]
1904 pub fn div_euc(self, rhs: Self) -> Self {
1907 return if rhs > 0 { q - 1 } else { q + 1 }
1915 concat!("Calculates the remainder `self mod rhs` by Euclidean division.
1917 In particular, the result `n` satisfies `0 <= n < rhs.abs()`.
1921 This function will panic if `rhs` is 0.
1928 #![feature(euclidean_division)]
1929 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1932 assert_eq!(a.mod_euc(b), 3);
1933 assert_eq!((-a).mod_euc(b), 1);
1934 assert_eq!(a.mod_euc(-b), 3);
1935 assert_eq!((-a).mod_euc(-b), 1);
1937 #[unstable(feature = "euclidean_division", issue = "49048")]
1939 #[rustc_inherit_overflow_checks]
1940 pub fn mod_euc(self, rhs: Self) -> Self {
1955 concat!("Computes the absolute value of `self`.
1959 The absolute value of `", stringify!($SelfT), "::min_value()` cannot be represented as an
1960 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
1961 code in debug mode will trigger a panic on this case and optimized code will return `",
1962 stringify!($SelfT), "::min_value()` without a panic.
1969 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
1970 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
1973 #[stable(feature = "rust1", since = "1.0.0")]
1975 #[rustc_inherit_overflow_checks]
1976 pub fn abs(self) -> Self {
1977 if self.is_negative() {
1978 // Note that the #[inline] above means that the overflow
1979 // semantics of this negation depend on the crate we're being
1989 concat!("Returns a number representing sign of `self`.
1991 - `0` if the number is zero
1992 - `1` if the number is positive
1993 - `-1` if the number is negative
2000 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
2001 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
2002 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
2005 #[stable(feature = "rust1", since = "1.0.0")]
2007 pub fn signum(self) -> Self {
2017 #[stable(feature = "rust1", since = "1.0.0")]
2020 pub fn is_positive(self) -> bool { self > 0 }
2023 concat!("Returns `true` if `self` is positive and `false` if the number is zero or
2031 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
2032 assert!(!(-10", stringify!($SelfT), ").is_positive());",
2035 #[stable(feature = "rust1", since = "1.0.0")]
2036 #[rustc_const_unstable(feature = "const_int_sign")]
2039 pub const fn is_positive(self) -> bool { self > 0 }
2043 #[stable(feature = "rust1", since = "1.0.0")]
2046 pub fn is_negative(self) -> bool { self < 0 }
2049 concat!("Returns `true` if `self` is negative and `false` if the number is zero or
2057 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
2058 assert!(!10", stringify!($SelfT), ".is_negative());",
2061 #[stable(feature = "rust1", since = "1.0.0")]
2062 #[rustc_const_unstable(feature = "const_int_sign")]
2065 pub const fn is_negative(self) -> bool { self < 0 }
2069 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
2072 pub fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2073 self.to_be().to_ne_bytes()
2077 concat!("Return the memory representation of this integer as a byte array in
2078 big-endian (network) byte order.
2083 #![feature(int_to_from_bytes)]
2085 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
2086 assert_eq!(bytes, ", $be_bytes, ");
2088 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
2089 #[rustc_const_unstable(feature = "const_int_conversion")]
2092 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2093 self.to_be().to_ne_bytes()
2098 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
2101 pub fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2102 self.to_le().to_ne_bytes()
2106 concat!("Return the memory representation of this integer as a byte array in
2107 little-endian byte order.
2112 #![feature(int_to_from_bytes)]
2114 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
2115 assert_eq!(bytes, ", $le_bytes, ");
2117 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
2118 #[rustc_const_unstable(feature = "const_int_conversion")]
2121 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2122 self.to_le().to_ne_bytes()
2127 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
2130 pub fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2131 unsafe { mem::transmute(self) }
2136 Return the memory representation of this integer as a byte array in
2139 As the target platform's native endianness is used, portable code
2140 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2143 [`to_be_bytes`]: #method.to_be_bytes
2144 [`to_le_bytes`]: #method.to_le_bytes
2149 #![feature(int_to_from_bytes)]
2151 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
2152 assert_eq!(bytes, if cfg!(target_endian = \"big\") {
2158 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
2159 #[rustc_const_unstable(feature = "const_int_conversion")]
2162 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2163 unsafe { mem::transmute(self) }
2168 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
2171 pub fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2172 Self::from_be(Self::from_ne_bytes(bytes))
2176 concat!("Create an integer value from its representation as a byte array in
2182 #![feature(int_to_from_bytes)]
2184 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
2185 assert_eq!(value, ", $swap_op, ");
2187 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
2188 #[rustc_const_unstable(feature = "const_int_conversion")]
2191 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2192 Self::from_be(Self::from_ne_bytes(bytes))
2197 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
2200 pub fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2201 Self::from_le(Self::from_ne_bytes(bytes))
2206 Create an integer value from its representation as a byte array in
2212 #![feature(int_to_from_bytes)]
2214 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
2215 assert_eq!(value, ", $swap_op, ");
2217 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
2218 #[rustc_const_unstable(feature = "const_int_conversion")]
2221 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2222 Self::from_le(Self::from_ne_bytes(bytes))
2227 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
2230 pub fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2231 unsafe { mem::transmute(bytes) }
2235 concat!("Create an integer value from its memory representation as a byte
2236 array in native endianness.
2238 As the target platform's native endianness is used, portable code
2239 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2240 appropriate instead.
2242 [`from_be_bytes`]: #method.from_be_bytes
2243 [`from_le_bytes`]: #method.from_le_bytes
2248 #![feature(int_to_from_bytes)]
2250 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
2255 assert_eq!(value, ", $swap_op, ");
2257 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
2258 #[rustc_const_unstable(feature = "const_int_conversion")]
2261 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2262 unsafe { mem::transmute(bytes) }
2270 int_impl! { i8, i8, u8, 8, -128, 127, "", "", 2, "-0x7e", "0xa", "0x12", "0x12", "0x48",
2271 "[0x12]", "[0x12]" }
2276 int_impl! { i16, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234", "0x3412",
2277 "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]" }
2282 int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2283 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2284 "[0x12, 0x34, 0x56, 0x78]" }
2289 int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "", 12,
2290 "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2291 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2292 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]" }
2297 int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
2298 170141183460469231731687303715884105727, "", "", 16,
2299 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
2300 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
2301 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
2302 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2303 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
2304 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]" }
2307 #[cfg(target_pointer_width = "16")]
2310 int_impl! { isize, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234",
2311 "0x3412", "0x2c48", "[0x34, 0x12]", "[0x12, 0x34]" }
2314 #[cfg(target_pointer_width = "32")]
2317 int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2318 "0x12345678", "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]",
2319 "[0x12, 0x34, 0x56, 0x78]" }
2322 #[cfg(target_pointer_width = "64")]
2325 int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "",
2326 12, "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2327 "0x6a2c48091e6a2c48", "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
2328 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]" }
2331 // Emits the correct `cttz` call, depending on the size of the type.
2332 macro_rules! uint_cttz_call {
2333 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
2334 // emits two conditional moves on x86_64. By promoting the value to
2335 // u16 and setting bit 8, we get better code without any conditional
2337 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
2338 // pending, remove this workaround once LLVM generates better code
2340 ($value:expr, 8) => { intrinsics::cttz($value as u16 | 0x100) };
2341 ($value:expr, $_BITS:expr) => { intrinsics::cttz($value) }
2344 // `Int` + `UnsignedInt` implemented for unsigned integers
2345 macro_rules! uint_impl {
2346 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr,
2347 $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
2348 $reversed:expr, $le_bytes:expr, $be_bytes:expr) => {
2350 concat!("Returns the smallest value that can be represented by this integer type.
2357 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), 0);", $EndFeature, "
2359 #[stable(feature = "rust1", since = "1.0.0")]
2361 pub const fn min_value() -> Self { 0 }
2365 concat!("Returns the largest value that can be represented by this integer type.
2372 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ",
2373 stringify!($MaxV), ");", $EndFeature, "
2375 #[stable(feature = "rust1", since = "1.0.0")]
2377 pub const fn max_value() -> Self { !0 }
2381 concat!("Converts a string slice in a given base to an integer.
2383 The string is expected to be an optional `+` sign
2385 Leading and trailing whitespace represent an error.
2386 Digits are a subset of these characters, depending on `radix`:
2394 This function panics if `radix` is not in the range from 2 to 36.
2401 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
2404 #[stable(feature = "rust1", since = "1.0.0")]
2405 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
2406 from_str_radix(src, radix)
2411 concat!("Returns the number of ones in the binary representation of `self`.
2418 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
2420 assert_eq!(n.count_ones(), 3);", $EndFeature, "
2422 #[stable(feature = "rust1", since = "1.0.0")]
2423 #[rustc_const_unstable(feature = "const_int_ops")]
2425 pub const fn count_ones(self) -> u32 {
2426 unsafe { intrinsics::ctpop(self as $ActualT) as u32 }
2431 concat!("Returns the number of zeros in the binary representation of `self`.
2438 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 0);", $EndFeature, "
2440 #[stable(feature = "rust1", since = "1.0.0")]
2441 #[rustc_const_unstable(feature = "const_int_ops")]
2443 pub const fn count_zeros(self) -> u32 {
2444 (!self).count_ones()
2449 concat!("Returns the number of leading zeros in the binary representation of `self`.
2456 ", $Feature, "let n = ", stringify!($SelfT), "::max_value() >> 2;
2458 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
2460 #[stable(feature = "rust1", since = "1.0.0")]
2461 #[rustc_const_unstable(feature = "const_int_ops")]
2463 pub const fn leading_zeros(self) -> u32 {
2464 unsafe { intrinsics::ctlz(self as $ActualT) as u32 }
2469 concat!("Returns the number of trailing zeros in the binary representation
2477 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
2479 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
2481 #[stable(feature = "rust1", since = "1.0.0")]
2482 #[rustc_const_unstable(feature = "const_int_ops")]
2484 pub const fn trailing_zeros(self) -> u32 {
2485 unsafe { uint_cttz_call!(self, $BITS) as u32 }
2490 #[stable(feature = "rust1", since = "1.0.0")]
2493 pub fn rotate_left(self, n: u32) -> Self {
2494 // Protect against undefined behaviour for over-long bit shifts
2496 (self << n) | (self >> (($BITS - n) % $BITS))
2500 concat!("Shifts the bits to the left by a specified amount, `n`,
2501 wrapping the truncated bits to the end of the resulting integer.
2503 Please note this isn't the same operation as `<<`!
2510 let n = ", $rot_op, stringify!($SelfT), ";
2511 let m = ", $rot_result, ";
2513 assert_eq!(n.rotate_left(", $rot, "), m);
2515 #[stable(feature = "rust1", since = "1.0.0")]
2516 #[rustc_const_unstable(feature = "const_int_rotate")]
2519 pub const fn rotate_left(self, n: u32) -> Self {
2520 (self << (n % $BITS)) | (self >> (($BITS - (n % $BITS)) % $BITS))
2525 #[stable(feature = "rust1", since = "1.0.0")]
2528 pub fn rotate_right(self, n: u32) -> Self {
2529 // Protect against undefined behaviour for over-long bit shifts
2531 (self >> n) | (self << (($BITS - n) % $BITS))
2535 concat!("Shifts the bits to the right by a specified amount, `n`,
2536 wrapping the truncated bits to the beginning of the resulting
2539 Please note this isn't the same operation as `>>`!
2546 let n = ", $rot_result, stringify!($SelfT), ";
2547 let m = ", $rot_op, ";
2549 assert_eq!(n.rotate_right(", $rot, "), m);
2551 #[stable(feature = "rust1", since = "1.0.0")]
2552 #[rustc_const_unstable(feature = "const_int_rotate")]
2555 pub const fn rotate_right(self, n: u32) -> Self {
2556 (self >> (n % $BITS)) | (self << (($BITS - (n % $BITS)) % $BITS))
2562 Reverses the byte order of the integer.
2569 let n = ", $swap_op, stringify!($SelfT), ";
2570 let m = n.swap_bytes();
2572 assert_eq!(m, ", $swapped, ");
2574 #[stable(feature = "rust1", since = "1.0.0")]
2575 #[rustc_const_unstable(feature = "const_int_ops")]
2577 pub const fn swap_bytes(self) -> Self {
2578 unsafe { intrinsics::bswap(self as $ActualT) as Self }
2583 #[unstable(feature = "reverse_bits", issue = "48763")]
2586 pub fn reverse_bits(self) -> Self {
2587 unsafe { intrinsics::bitreverse(self as $ActualT) as Self }
2591 concat!("Reverses the bit pattern of the integer.
2598 #![feature(reverse_bits)]
2600 let n = ", $swap_op, stringify!($SelfT), ";
2601 let m = n.reverse_bits();
2603 assert_eq!(m, ", $reversed, ");
2605 #[unstable(feature = "reverse_bits", issue = "48763")]
2606 #[rustc_const_unstable(feature = "const_int_conversion")]
2609 pub const fn reverse_bits(self) -> Self {
2610 unsafe { intrinsics::bitreverse(self as $ActualT) as Self }
2615 concat!("Converts an integer from big endian to the target's endianness.
2617 On big endian this is a no-op. On little endian the bytes are
2625 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2627 if cfg!(target_endian = \"big\") {
2628 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
2630 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
2633 #[stable(feature = "rust1", since = "1.0.0")]
2634 #[rustc_const_unstable(feature = "const_int_ops")]
2636 pub const fn from_be(x: Self) -> Self {
2637 #[cfg(target_endian = "big")]
2641 #[cfg(not(target_endian = "big"))]
2649 concat!("Converts an integer from little endian to the target's endianness.
2651 On little endian this is a no-op. On big endian the bytes are
2659 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2661 if cfg!(target_endian = \"little\") {
2662 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
2664 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
2667 #[stable(feature = "rust1", since = "1.0.0")]
2668 #[rustc_const_unstable(feature = "const_int_ops")]
2670 pub const fn from_le(x: Self) -> Self {
2671 #[cfg(target_endian = "little")]
2675 #[cfg(not(target_endian = "little"))]
2683 concat!("Converts `self` to big endian from the target's endianness.
2685 On big endian this is a no-op. On little endian the bytes are
2693 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2695 if cfg!(target_endian = \"big\") {
2696 assert_eq!(n.to_be(), n)
2698 assert_eq!(n.to_be(), n.swap_bytes())
2701 #[stable(feature = "rust1", since = "1.0.0")]
2702 #[rustc_const_unstable(feature = "const_int_ops")]
2704 pub const fn to_be(self) -> Self { // or not to be?
2705 #[cfg(target_endian = "big")]
2709 #[cfg(not(target_endian = "big"))]
2717 concat!("Converts `self` to little endian from the target's endianness.
2719 On little endian this is a no-op. On big endian the bytes are
2727 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2729 if cfg!(target_endian = \"little\") {
2730 assert_eq!(n.to_le(), n)
2732 assert_eq!(n.to_le(), n.swap_bytes())
2735 #[stable(feature = "rust1", since = "1.0.0")]
2736 #[rustc_const_unstable(feature = "const_int_ops")]
2738 pub const fn to_le(self) -> Self {
2739 #[cfg(target_endian = "little")]
2743 #[cfg(not(target_endian = "little"))]
2751 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2752 if overflow occurred.
2759 ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), ",
2760 "Some(", stringify!($SelfT), "::max_value() - 1));
2761 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);", $EndFeature, "
2763 #[stable(feature = "rust1", since = "1.0.0")]
2765 pub fn checked_add(self, rhs: Self) -> Option<Self> {
2766 let (a, b) = self.overflowing_add(rhs);
2767 if b {None} else {Some(a)}
2772 concat!("Checked integer subtraction. Computes `self - rhs`, returning
2773 `None` if overflow occurred.
2780 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
2781 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
2783 #[stable(feature = "rust1", since = "1.0.0")]
2785 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
2786 let (a, b) = self.overflowing_sub(rhs);
2787 if b {None} else {Some(a)}
2792 concat!("Checked integer multiplication. Computes `self * rhs`, returning
2793 `None` if overflow occurred.
2800 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
2801 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, "
2803 #[stable(feature = "rust1", since = "1.0.0")]
2805 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
2806 let (a, b) = self.overflowing_mul(rhs);
2807 if b {None} else {Some(a)}
2812 concat!("Checked integer division. Computes `self / rhs`, returning `None`
2820 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2821 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2823 #[stable(feature = "rust1", since = "1.0.0")]
2825 pub fn checked_div(self, rhs: Self) -> Option<Self> {
2828 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
2834 concat!("Checked Euclidean division. Computes `self.div_euc(rhs)`, returning `None`
2842 #![feature(euclidean_division)]
2843 assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2844 assert_eq!(1", stringify!($SelfT), ".checked_div_euc(0), None);
2846 #[unstable(feature = "euclidean_division", issue = "49048")]
2848 pub fn checked_div_euc(self, rhs: Self) -> Option<Self> {
2852 Some(self.div_euc(rhs))
2859 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
2867 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
2868 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
2870 #[stable(feature = "wrapping", since = "1.7.0")]
2872 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
2876 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
2882 concat!("Checked Euclidean modulo. Computes `self.mod_euc(rhs)`, returning `None`
2890 #![feature(euclidean_division)]
2891 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(2), Some(1));
2892 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(0), None);
2894 #[unstable(feature = "euclidean_division", issue = "49048")]
2896 pub fn checked_mod_euc(self, rhs: Self) -> Option<Self> {
2900 Some(self.mod_euc(rhs))
2906 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
2909 Note that negating any positive integer will overflow.
2916 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
2917 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
2919 #[stable(feature = "wrapping", since = "1.7.0")]
2921 pub fn checked_neg(self) -> Option<Self> {
2922 let (a, b) = self.overflowing_neg();
2923 if b {None} else {Some(a)}
2928 concat!("Checked shift left. Computes `self << rhs`, returning `None`
2929 if `rhs` is larger than or equal to the number of bits in `self`.
2936 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
2937 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
2939 #[stable(feature = "wrapping", since = "1.7.0")]
2941 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
2942 let (a, b) = self.overflowing_shl(rhs);
2943 if b {None} else {Some(a)}
2948 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
2949 if `rhs` is larger than or equal to the number of bits in `self`.
2956 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
2957 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
2959 #[stable(feature = "wrapping", since = "1.7.0")]
2961 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
2962 let (a, b) = self.overflowing_shr(rhs);
2963 if b {None} else {Some(a)}
2968 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
2976 #![feature(no_panic_pow)]
2977 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
2978 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, "
2980 #[unstable(feature = "no_panic_pow", issue = "48320")]
2982 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
2983 let mut base = self;
2984 let mut acc: Self = 1;
2988 acc = acc.checked_mul(base)?;
2991 base = base.checked_mul(base)?;
2994 // Deal with the final bit of the exponent separately, since
2995 // squaring the base afterwards is not necessary and may cause a
2996 // needless overflow.
2998 acc = acc.checked_mul(base)?;
3006 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
3007 the numeric bounds instead of overflowing.
3014 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
3015 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
3017 #[stable(feature = "rust1", since = "1.0.0")]
3019 pub fn saturating_add(self, rhs: Self) -> Self {
3020 match self.checked_add(rhs) {
3022 None => Self::max_value(),
3028 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
3029 at the numeric bounds instead of overflowing.
3036 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
3037 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
3039 #[stable(feature = "rust1", since = "1.0.0")]
3041 pub fn saturating_sub(self, rhs: Self) -> Self {
3042 match self.checked_sub(rhs) {
3044 None => Self::min_value(),
3050 concat!("Saturating integer multiplication. Computes `self * rhs`,
3051 saturating at the numeric bounds instead of overflowing.
3058 ", $Feature, "use std::", stringify!($SelfT), ";
3060 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
3061 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
3062 "::MAX);", $EndFeature, "
3064 #[stable(feature = "wrapping", since = "1.7.0")]
3066 pub fn saturating_mul(self, rhs: Self) -> Self {
3067 self.checked_mul(rhs).unwrap_or(Self::max_value())
3072 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
3073 saturating at the numeric bounds instead of overflowing.
3080 #![feature(no_panic_pow)]
3081 ", $Feature, "use std::", stringify!($SelfT), ";
3083 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
3084 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
3087 #[unstable(feature = "no_panic_pow", issue = "48320")]
3089 pub fn saturating_pow(self, exp: u32) -> Self {
3090 match self.checked_pow(exp) {
3092 None => Self::max_value(),
3098 #[stable(feature = "rust1", since = "1.0.0")]
3101 pub fn wrapping_add(self, rhs: Self) -> Self {
3103 intrinsics::overflowing_add(self, rhs)
3108 concat!("Wrapping (modular) addition. Computes `self + rhs`,
3109 wrapping around at the boundary of the type.
3116 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
3117 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
3120 #[stable(feature = "rust1", since = "1.0.0")]
3121 #[rustc_const_unstable(feature = "const_int_wrapping")]
3124 pub const fn wrapping_add(self, rhs: Self) -> Self {
3126 intrinsics::overflowing_add(self, rhs)
3132 #[stable(feature = "rust1", since = "1.0.0")]
3135 pub fn wrapping_sub(self, rhs: Self) -> Self {
3137 intrinsics::overflowing_sub(self, rhs)
3142 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
3143 wrapping around at the boundary of the type.
3150 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
3151 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
3154 #[stable(feature = "rust1", since = "1.0.0")]
3155 #[rustc_const_unstable(feature = "const_int_wrapping")]
3158 pub const fn wrapping_sub(self, rhs: Self) -> Self {
3160 intrinsics::overflowing_sub(self, rhs)
3166 #[stable(feature = "rust1", since = "1.0.0")]
3169 pub fn wrapping_mul(self, rhs: Self) -> Self {
3171 intrinsics::overflowing_mul(self, rhs)
3175 /// Wrapping (modular) multiplication. Computes `self *
3176 /// rhs`, wrapping around at the boundary of the type.
3182 /// Please note that this example is shared between integer types.
3183 /// Which explains why `u8` is used here.
3186 /// assert_eq!(10u8.wrapping_mul(12), 120);
3187 /// assert_eq!(25u8.wrapping_mul(12), 44);
3189 #[stable(feature = "rust1", since = "1.0.0")]
3190 #[rustc_const_unstable(feature = "const_int_wrapping")]
3193 pub const fn wrapping_mul(self, rhs: Self) -> Self {
3195 intrinsics::overflowing_mul(self, rhs)
3200 concat!("Wrapping (modular) division. Computes `self / rhs`.
3201 Wrapped division on unsigned types is just normal division.
3202 There's no way wrapping could ever happen.
3203 This function exists, so that all operations
3204 are accounted for in the wrapping operations.
3211 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
3213 #[stable(feature = "num_wrapping", since = "1.2.0")]
3215 pub fn wrapping_div(self, rhs: Self) -> Self {
3221 concat!("Wrapping Euclidean division. Computes `self.div_euc(rhs)`.
3222 Wrapped division on unsigned types is just normal division.
3223 There's no way wrapping could ever happen.
3224 This function exists, so that all operations
3225 are accounted for in the wrapping operations.
3232 #![feature(euclidean_division)]
3233 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euc(10), 10);
3235 #[unstable(feature = "euclidean_division", issue = "49048")]
3237 pub fn wrapping_div_euc(self, rhs: Self) -> Self {
3243 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
3244 Wrapped remainder calculation on unsigned types is
3245 just the regular remainder calculation.
3246 There's no way wrapping could ever happen.
3247 This function exists, so that all operations
3248 are accounted for in the wrapping operations.
3255 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
3257 #[stable(feature = "num_wrapping", since = "1.2.0")]
3259 pub fn wrapping_rem(self, rhs: Self) -> Self {
3265 concat!("Wrapping Euclidean modulo. Computes `self.mod_euc(rhs)`.
3266 Wrapped modulo calculation on unsigned types is
3267 just the regular remainder calculation.
3268 There's no way wrapping could ever happen.
3269 This function exists, so that all operations
3270 are accounted for in the wrapping operations.
3277 #![feature(euclidean_division)]
3278 assert_eq!(100", stringify!($SelfT), ".wrapping_mod_euc(10), 0);
3280 #[unstable(feature = "euclidean_division", issue = "49048")]
3282 pub fn wrapping_mod_euc(self, rhs: Self) -> Self {
3287 /// Wrapping (modular) negation. Computes `-self`,
3288 /// wrapping around at the boundary of the type.
3290 /// Since unsigned types do not have negative equivalents
3291 /// all applications of this function will wrap (except for `-0`).
3292 /// For values smaller than the corresponding signed type's maximum
3293 /// the result is the same as casting the corresponding signed value.
3294 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
3295 /// `MAX` is the corresponding signed type's maximum.
3301 /// Please note that this example is shared between integer types.
3302 /// Which explains why `i8` is used here.
3305 /// assert_eq!(100i8.wrapping_neg(), -100);
3306 /// assert_eq!((-128i8).wrapping_neg(), -128);
3308 #[stable(feature = "num_wrapping", since = "1.2.0")]
3310 pub fn wrapping_neg(self) -> Self {
3311 self.overflowing_neg().0
3315 #[stable(feature = "num_wrapping", since = "1.2.0")]
3318 pub fn wrapping_shl(self, rhs: u32) -> Self {
3320 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
3325 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
3326 where `mask` removes any high-order bits of `rhs` that
3327 would cause the shift to exceed the bitwidth of the type.
3329 Note that this is *not* the same as a rotate-left; the
3330 RHS of a wrapping shift-left is restricted to the range
3331 of the type, rather than the bits shifted out of the LHS
3332 being returned to the other end. The primitive integer
3333 types all implement a `rotate_left` function, which may
3334 be what you want instead.
3341 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
3342 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
3344 #[stable(feature = "num_wrapping", since = "1.2.0")]
3345 #[rustc_const_unstable(feature = "const_int_wrapping")]
3348 pub const fn wrapping_shl(self, rhs: u32) -> Self {
3350 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
3356 #[stable(feature = "num_wrapping", since = "1.2.0")]
3359 pub fn wrapping_shr(self, rhs: u32) -> Self {
3361 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
3366 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
3367 where `mask` removes any high-order bits of `rhs` that
3368 would cause the shift to exceed the bitwidth of the type.
3370 Note that this is *not* the same as a rotate-right; the
3371 RHS of a wrapping shift-right is restricted to the range
3372 of the type, rather than the bits shifted out of the LHS
3373 being returned to the other end. The primitive integer
3374 types all implement a `rotate_right` function, which may
3375 be what you want instead.
3382 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
3383 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
3385 #[stable(feature = "num_wrapping", since = "1.2.0")]
3386 #[rustc_const_unstable(feature = "const_int_wrapping")]
3389 pub const fn wrapping_shr(self, rhs: u32) -> Self {
3391 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
3397 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
3398 wrapping around at the boundary of the type.
3405 #![feature(no_panic_pow)]
3406 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
3407 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
3409 #[unstable(feature = "no_panic_pow", issue = "48320")]
3411 pub fn wrapping_pow(self, mut exp: u32) -> Self {
3412 let mut base = self;
3413 let mut acc: Self = 1;
3417 acc = acc.wrapping_mul(base);
3420 base = base.wrapping_mul(base);
3423 // Deal with the final bit of the exponent separately, since
3424 // squaring the base afterwards is not necessary and may cause a
3425 // needless overflow.
3427 acc = acc.wrapping_mul(base);
3435 #[stable(feature = "wrapping", since = "1.7.0")]
3438 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
3439 let (a, b) = unsafe {
3440 intrinsics::add_with_overflow(self as $ActualT,
3447 concat!("Calculates `self` + `rhs`
3449 Returns a tuple of the addition along with a boolean indicating
3450 whether an arithmetic overflow would occur. If an overflow would
3451 have occurred then the wrapped value is returned.
3458 ", $Feature, "use std::", stringify!($SelfT), ";
3460 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
3461 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
3463 #[stable(feature = "wrapping", since = "1.7.0")]
3464 #[rustc_const_unstable(feature = "const_int_overflowing")]
3467 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
3468 let (a, b) = unsafe {
3469 intrinsics::add_with_overflow(self as $ActualT,
3477 #[stable(feature = "wrapping", since = "1.7.0")]
3480 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3481 let (a, b) = unsafe {
3482 intrinsics::sub_with_overflow(self as $ActualT,
3489 concat!("Calculates `self` - `rhs`
3491 Returns a tuple of the subtraction along with a boolean indicating
3492 whether an arithmetic overflow would occur. If an overflow would
3493 have occurred then the wrapped value is returned.
3500 ", $Feature, "use std::", stringify!($SelfT), ";
3502 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
3503 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
3506 #[stable(feature = "wrapping", since = "1.7.0")]
3507 #[rustc_const_unstable(feature = "const_int_overflowing")]
3510 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3511 let (a, b) = unsafe {
3512 intrinsics::sub_with_overflow(self as $ActualT,
3520 #[stable(feature = "wrapping", since = "1.7.0")]
3523 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3524 let (a, b) = unsafe {
3525 intrinsics::mul_with_overflow(self as $ActualT,
3531 /// Calculates the multiplication of `self` and `rhs`.
3533 /// Returns a tuple of the multiplication along with a boolean
3534 /// indicating whether an arithmetic overflow would occur. If an
3535 /// overflow would have occurred then the wrapped value is returned.
3541 /// Please note that this example is shared between integer types.
3542 /// Which explains why `u32` is used here.
3545 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3546 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3548 #[stable(feature = "wrapping", since = "1.7.0")]
3549 #[rustc_const_unstable(feature = "const_int_overflowing")]
3552 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3553 let (a, b) = unsafe {
3554 intrinsics::mul_with_overflow(self as $ActualT,
3561 concat!("Calculates the divisor when `self` is divided by `rhs`.
3563 Returns a tuple of the divisor along with a boolean indicating
3564 whether an arithmetic overflow would occur. Note that for unsigned
3565 integers overflow never occurs, so the second value is always
3570 This function will panic if `rhs` is 0.
3577 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
3580 #[stable(feature = "wrapping", since = "1.7.0")]
3581 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3587 concat!("Calculates the quotient of Euclidean division `self.div_euc(rhs)`.
3589 Returns a tuple of the divisor along with a boolean indicating
3590 whether an arithmetic overflow would occur. Note that for unsigned
3591 integers overflow never occurs, so the second value is always
3596 This function will panic if `rhs` is 0.
3603 #![feature(euclidean_division)]
3604 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euc(2), (2, false));
3607 #[unstable(feature = "euclidean_division", issue = "49048")]
3608 pub fn overflowing_div_euc(self, rhs: Self) -> (Self, bool) {
3614 concat!("Calculates the remainder when `self` is divided by `rhs`.
3616 Returns a tuple of the remainder after dividing along with a boolean
3617 indicating whether an arithmetic overflow would occur. Note that for
3618 unsigned integers overflow never occurs, so the second value is
3623 This function will panic if `rhs` is 0.
3630 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3633 #[stable(feature = "wrapping", since = "1.7.0")]
3634 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3640 concat!("Calculates the remainder `self.mod_euc(rhs)` by Euclidean division.
3642 Returns a tuple of the modulo after dividing along with a boolean
3643 indicating whether an arithmetic overflow would occur. Note that for
3644 unsigned integers overflow never occurs, so the second value is
3649 This function will panic if `rhs` is 0.
3656 #![feature(euclidean_division)]
3657 assert_eq!(5", stringify!($SelfT), ".overflowing_mod_euc(2), (1, false));
3660 #[unstable(feature = "euclidean_division", issue = "49048")]
3661 pub fn overflowing_mod_euc(self, rhs: Self) -> (Self, bool) {
3667 concat!("Negates self in an overflowing fashion.
3669 Returns `!self + 1` using wrapping operations to return the value
3670 that represents the negation of this unsigned value. Note that for
3671 positive unsigned values overflow always occurs, but negating 0 does
3679 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3680 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3681 ", true));", $EndFeature, "
3684 #[stable(feature = "wrapping", since = "1.7.0")]
3685 pub fn overflowing_neg(self) -> (Self, bool) {
3686 ((!self).wrapping_add(1), self != 0)
3691 #[stable(feature = "wrapping", since = "1.7.0")]
3694 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3695 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3699 concat!("Shifts self left by `rhs` bits.
3701 Returns a tuple of the shifted version of self along with a boolean
3702 indicating whether the shift value was larger than or equal to the
3703 number of bits. If the shift value is too large, then value is
3704 masked (N-1) where N is the number of bits, and this value is then
3705 used to perform the shift.
3712 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3713 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3715 #[stable(feature = "wrapping", since = "1.7.0")]
3716 #[rustc_const_unstable(feature = "const_int_overflowing")]
3719 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3720 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3725 #[stable(feature = "wrapping", since = "1.7.0")]
3728 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3729 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
3733 concat!("Shifts self right by `rhs` bits.
3735 Returns a tuple of the shifted version of self along with a boolean
3736 indicating whether the shift value was larger than or equal to the
3737 number of bits. If the shift value is too large, then value is
3738 masked (N-1) where N is the number of bits, and this value is then
3739 used to perform the shift.
3746 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
3747 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
3749 #[stable(feature = "wrapping", since = "1.7.0")]
3750 #[rustc_const_unstable(feature = "const_int_overflowing")]
3753 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3754 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
3759 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3761 Returns a tuple of the exponentiation along with a bool indicating
3762 whether an overflow happened.
3769 #![feature(no_panic_pow)]
3770 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
3771 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
3773 #[unstable(feature = "no_panic_pow", issue = "48320")]
3775 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3776 let mut base = self;
3777 let mut acc: Self = 1;
3778 let mut overflown = false;
3779 // Scratch space for storing results of overflowing_mul.
3784 r = acc.overflowing_mul(base);
3789 r = base.overflowing_mul(base);
3794 // Deal with the final bit of the exponent separately, since
3795 // squaring the base afterwards is not necessary and may cause a
3796 // needless overflow.
3798 r = acc.overflowing_mul(base);
3808 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3815 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
3817 #[stable(feature = "rust1", since = "1.0.0")]
3819 #[rustc_inherit_overflow_checks]
3820 pub fn pow(self, mut exp: u32) -> Self {
3821 let mut base = self;
3832 // Deal with the final bit of the exponent separately, since
3833 // squaring the base afterwards is not necessary and may cause a
3834 // needless overflow.
3844 concat!("Performs Euclidean division.
3846 For unsigned types, this is just the same as `self / rhs`.
3853 #![feature(euclidean_division)]
3854 assert_eq!(7", stringify!($SelfT), ".div_euc(4), 1); // or any other integer type
3856 #[unstable(feature = "euclidean_division", issue = "49048")]
3858 #[rustc_inherit_overflow_checks]
3859 pub fn div_euc(self, rhs: Self) -> Self {
3866 concat!("Calculates the remainder `self mod rhs` by Euclidean division.
3868 For unsigned types, this is just the same as `self % rhs`.
3875 #![feature(euclidean_division)]
3876 assert_eq!(7", stringify!($SelfT), ".mod_euc(4), 3); // or any other integer type
3878 #[unstable(feature = "euclidean_division", issue = "49048")]
3880 #[rustc_inherit_overflow_checks]
3881 pub fn mod_euc(self, rhs: Self) -> Self {
3887 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
3894 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
3895 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
3897 #[stable(feature = "rust1", since = "1.0.0")]
3899 pub fn is_power_of_two(self) -> bool {
3900 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
3904 // Returns one less than next power of two.
3905 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
3907 // 8u8.one_less_than_next_power_of_two() == 7
3908 // 6u8.one_less_than_next_power_of_two() == 7
3910 // This method cannot overflow, as in the `next_power_of_two`
3911 // overflow cases it instead ends up returning the maximum value
3912 // of the type, and can return 0 for 0.
3914 fn one_less_than_next_power_of_two(self) -> Self {
3915 if self <= 1 { return 0; }
3917 // Because `p > 0`, it cannot consist entirely of leading zeros.
3918 // That means the shift is always in-bounds, and some processors
3919 // (such as intel pre-haswell) have more efficient ctlz
3920 // intrinsics when the argument is non-zero.
3922 let z = unsafe { intrinsics::ctlz_nonzero(p) };
3923 <$SelfT>::max_value() >> z
3927 concat!("Returns the smallest power of two greater than or equal to `self`.
3929 When return value overflows (i.e. `self > (1 << (N-1))` for type
3930 `uN`), it panics in debug mode and return value is wrapped to 0 in
3931 release mode (the only situation in which method can return 0).
3938 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
3939 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
3941 #[stable(feature = "rust1", since = "1.0.0")]
3943 pub fn next_power_of_two(self) -> Self {
3944 // Call the trait to get overflow checks
3945 ops::Add::add(self.one_less_than_next_power_of_two(), 1)
3950 concat!("Returns the smallest power of two greater than or equal to `n`. If
3951 the next power of two is greater than the type's maximum value,
3952 `None` is returned, otherwise the power of two is wrapped in `Some`.
3959 ", $Feature, "assert_eq!(2", stringify!($SelfT),
3960 ".checked_next_power_of_two(), Some(2));
3961 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
3962 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
3965 #[stable(feature = "rust1", since = "1.0.0")]
3966 pub fn checked_next_power_of_two(self) -> Option<Self> {
3967 self.one_less_than_next_power_of_two().checked_add(1)
3972 concat!("Returns the smallest power of two greater than or equal to `n`. If
3973 the next power of two is greater than the type's maximum value,
3974 the return value is wrapped to `0`.
3981 #![feature(wrapping_next_power_of_two)]
3983 assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);
3984 assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);
3985 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_next_power_of_two(), 0);",
3988 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
3989 reason = "needs decision on wrapping behaviour")]
3990 pub fn wrapping_next_power_of_two(self) -> Self {
3991 self.one_less_than_next_power_of_two().wrapping_add(1)
3996 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
3999 pub fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
4000 self.to_be().to_ne_bytes()
4004 concat!("Return the memory representation of this integer as a byte array in
4005 big-endian (network) byte order.
4010 #![feature(int_to_from_bytes)]
4012 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
4013 assert_eq!(bytes, ", $be_bytes, ");
4015 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
4016 #[rustc_const_unstable(feature = "const_int_conversion")]
4019 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
4020 self.to_be().to_ne_bytes()
4025 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
4028 pub fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
4029 self.to_le().to_ne_bytes()
4033 concat!("Return the memory representation of this integer as a byte array in
4034 little-endian byte order.
4039 #![feature(int_to_from_bytes)]
4041 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
4042 assert_eq!(bytes, ", $le_bytes, ");
4044 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
4045 #[rustc_const_unstable(feature = "const_int_conversion")]
4048 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
4049 self.to_le().to_ne_bytes()
4054 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
4057 pub fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
4058 unsafe { mem::transmute(self) }
4063 Return the memory representation of this integer as a byte array in
4066 As the target platform's native endianness is used, portable code
4067 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
4070 [`to_be_bytes`]: #method.to_be_bytes
4071 [`to_le_bytes`]: #method.to_le_bytes
4076 #![feature(int_to_from_bytes)]
4078 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
4079 assert_eq!(bytes, if cfg!(target_endian = \"big\") {
4085 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
4086 #[rustc_const_unstable(feature = "const_int_conversion")]
4089 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
4090 unsafe { mem::transmute(self) }
4095 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
4098 pub fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4099 Self::from_be(Self::from_ne_bytes(bytes))
4103 concat!("Create an integer value from its representation as a byte array in
4109 #![feature(int_to_from_bytes)]
4111 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
4112 assert_eq!(value, ", $swap_op, ");
4114 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
4115 #[rustc_const_unstable(feature = "const_int_conversion")]
4118 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4119 Self::from_be(Self::from_ne_bytes(bytes))
4124 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
4127 pub fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4128 Self::from_le(Self::from_ne_bytes(bytes))
4133 Create an integer value from its representation as a byte array in
4139 #![feature(int_to_from_bytes)]
4141 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
4142 assert_eq!(value, ", $swap_op, ");
4144 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
4145 #[rustc_const_unstable(feature = "const_int_conversion")]
4148 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4149 Self::from_le(Self::from_ne_bytes(bytes))
4154 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
4157 pub fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4158 unsafe { mem::transmute(bytes) }
4162 concat!("Create an integer value from its memory representation as a byte
4163 array in native endianness.
4165 As the target platform's native endianness is used, portable code
4166 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
4167 appropriate instead.
4169 [`from_be_bytes`]: #method.from_be_bytes
4170 [`from_le_bytes`]: #method.from_le_bytes
4175 #![feature(int_to_from_bytes)]
4177 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
4182 assert_eq!(value, ", $swap_op, ");
4184 #[unstable(feature = "int_to_from_bytes", issue = "52963")]
4185 #[rustc_const_unstable(feature = "const_int_conversion")]
4188 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
4189 unsafe { mem::transmute(bytes) }
4197 uint_impl! { u8, u8, 8, 255, "", "", 2, "0x82", "0xa", "0x12", "0x12", "0x48", "[0x12]",
4201 /// Checks if the value is within the ASCII range.
4206 /// let ascii = 97u8;
4207 /// let non_ascii = 150u8;
4209 /// assert!(ascii.is_ascii());
4210 /// assert!(!non_ascii.is_ascii());
4212 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4214 pub fn is_ascii(&self) -> bool {
4218 /// Makes a copy of the value in its ASCII upper case equivalent.
4220 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4221 /// but non-ASCII letters are unchanged.
4223 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
4228 /// let lowercase_a = 97u8;
4230 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
4233 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
4234 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4236 pub fn to_ascii_uppercase(&self) -> u8 {
4237 ASCII_UPPERCASE_MAP[*self as usize]
4240 /// Makes a copy of the value in its ASCII lower case equivalent.
4242 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4243 /// but non-ASCII letters are unchanged.
4245 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
4250 /// let uppercase_a = 65u8;
4252 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
4255 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
4256 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4258 pub fn to_ascii_lowercase(&self) -> u8 {
4259 ASCII_LOWERCASE_MAP[*self as usize]
4262 /// Checks that two values are an ASCII case-insensitive match.
4264 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
4269 /// let lowercase_a = 97u8;
4270 /// let uppercase_a = 65u8;
4272 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
4274 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4276 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
4277 self.to_ascii_lowercase() == other.to_ascii_lowercase()
4280 /// Converts this value to its ASCII upper case equivalent in-place.
4282 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
4283 /// but non-ASCII letters are unchanged.
4285 /// To return a new uppercased value without modifying the existing one, use
4286 /// [`to_ascii_uppercase`].
4291 /// let mut byte = b'a';
4293 /// byte.make_ascii_uppercase();
4295 /// assert_eq!(b'A', byte);
4298 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
4299 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4301 pub fn make_ascii_uppercase(&mut self) {
4302 *self = self.to_ascii_uppercase();
4305 /// Converts this value to its ASCII lower case equivalent in-place.
4307 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
4308 /// but non-ASCII letters are unchanged.
4310 /// To return a new lowercased value without modifying the existing one, use
4311 /// [`to_ascii_lowercase`].
4316 /// let mut byte = b'A';
4318 /// byte.make_ascii_lowercase();
4320 /// assert_eq!(b'a', byte);
4323 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
4324 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
4326 pub fn make_ascii_lowercase(&mut self) {
4327 *self = self.to_ascii_lowercase();
4330 /// Checks if the value is an ASCII alphabetic character:
4332 /// - U+0041 'A' ... U+005A 'Z', or
4333 /// - U+0061 'a' ... U+007A 'z'.
4338 /// let uppercase_a = b'A';
4339 /// let uppercase_g = b'G';
4342 /// let zero = b'0';
4343 /// let percent = b'%';
4344 /// let space = b' ';
4346 /// let esc = 0x1b_u8;
4348 /// assert!(uppercase_a.is_ascii_alphabetic());
4349 /// assert!(uppercase_g.is_ascii_alphabetic());
4350 /// assert!(a.is_ascii_alphabetic());
4351 /// assert!(g.is_ascii_alphabetic());
4352 /// assert!(!zero.is_ascii_alphabetic());
4353 /// assert!(!percent.is_ascii_alphabetic());
4354 /// assert!(!space.is_ascii_alphabetic());
4355 /// assert!(!lf.is_ascii_alphabetic());
4356 /// assert!(!esc.is_ascii_alphabetic());
4358 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4360 pub fn is_ascii_alphabetic(&self) -> bool {
4361 if *self >= 0x80 { return false; }
4362 match ASCII_CHARACTER_CLASS[*self as usize] {
4363 L | Lx | U | Ux => true,
4368 /// Checks if the value is an ASCII uppercase character:
4369 /// U+0041 'A' ... U+005A 'Z'.
4374 /// let uppercase_a = b'A';
4375 /// let uppercase_g = b'G';
4378 /// let zero = b'0';
4379 /// let percent = b'%';
4380 /// let space = b' ';
4382 /// let esc = 0x1b_u8;
4384 /// assert!(uppercase_a.is_ascii_uppercase());
4385 /// assert!(uppercase_g.is_ascii_uppercase());
4386 /// assert!(!a.is_ascii_uppercase());
4387 /// assert!(!g.is_ascii_uppercase());
4388 /// assert!(!zero.is_ascii_uppercase());
4389 /// assert!(!percent.is_ascii_uppercase());
4390 /// assert!(!space.is_ascii_uppercase());
4391 /// assert!(!lf.is_ascii_uppercase());
4392 /// assert!(!esc.is_ascii_uppercase());
4394 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4396 pub fn is_ascii_uppercase(&self) -> bool {
4397 if *self >= 0x80 { return false }
4398 match ASCII_CHARACTER_CLASS[*self as usize] {
4404 /// Checks if the value is an ASCII lowercase character:
4405 /// U+0061 'a' ... U+007A 'z'.
4410 /// let uppercase_a = b'A';
4411 /// let uppercase_g = b'G';
4414 /// let zero = b'0';
4415 /// let percent = b'%';
4416 /// let space = b' ';
4418 /// let esc = 0x1b_u8;
4420 /// assert!(!uppercase_a.is_ascii_lowercase());
4421 /// assert!(!uppercase_g.is_ascii_lowercase());
4422 /// assert!(a.is_ascii_lowercase());
4423 /// assert!(g.is_ascii_lowercase());
4424 /// assert!(!zero.is_ascii_lowercase());
4425 /// assert!(!percent.is_ascii_lowercase());
4426 /// assert!(!space.is_ascii_lowercase());
4427 /// assert!(!lf.is_ascii_lowercase());
4428 /// assert!(!esc.is_ascii_lowercase());
4430 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4432 pub fn is_ascii_lowercase(&self) -> bool {
4433 if *self >= 0x80 { return false }
4434 match ASCII_CHARACTER_CLASS[*self as usize] {
4440 /// Checks if the value is an ASCII alphanumeric character:
4442 /// - U+0041 'A' ... U+005A 'Z', or
4443 /// - U+0061 'a' ... U+007A 'z', or
4444 /// - U+0030 '0' ... U+0039 '9'.
4449 /// let uppercase_a = b'A';
4450 /// let uppercase_g = b'G';
4453 /// let zero = b'0';
4454 /// let percent = b'%';
4455 /// let space = b' ';
4457 /// let esc = 0x1b_u8;
4459 /// assert!(uppercase_a.is_ascii_alphanumeric());
4460 /// assert!(uppercase_g.is_ascii_alphanumeric());
4461 /// assert!(a.is_ascii_alphanumeric());
4462 /// assert!(g.is_ascii_alphanumeric());
4463 /// assert!(zero.is_ascii_alphanumeric());
4464 /// assert!(!percent.is_ascii_alphanumeric());
4465 /// assert!(!space.is_ascii_alphanumeric());
4466 /// assert!(!lf.is_ascii_alphanumeric());
4467 /// assert!(!esc.is_ascii_alphanumeric());
4469 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4471 pub fn is_ascii_alphanumeric(&self) -> bool {
4472 if *self >= 0x80 { return false }
4473 match ASCII_CHARACTER_CLASS[*self as usize] {
4474 D | L | Lx | U | Ux => true,
4479 /// Checks if the value is an ASCII decimal digit:
4480 /// U+0030 '0' ... U+0039 '9'.
4485 /// let uppercase_a = b'A';
4486 /// let uppercase_g = b'G';
4489 /// let zero = b'0';
4490 /// let percent = b'%';
4491 /// let space = b' ';
4493 /// let esc = 0x1b_u8;
4495 /// assert!(!uppercase_a.is_ascii_digit());
4496 /// assert!(!uppercase_g.is_ascii_digit());
4497 /// assert!(!a.is_ascii_digit());
4498 /// assert!(!g.is_ascii_digit());
4499 /// assert!(zero.is_ascii_digit());
4500 /// assert!(!percent.is_ascii_digit());
4501 /// assert!(!space.is_ascii_digit());
4502 /// assert!(!lf.is_ascii_digit());
4503 /// assert!(!esc.is_ascii_digit());
4505 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4507 pub fn is_ascii_digit(&self) -> bool {
4508 if *self >= 0x80 { return false }
4509 match ASCII_CHARACTER_CLASS[*self as usize] {
4515 /// Checks if the value is an ASCII hexadecimal digit:
4517 /// - U+0030 '0' ... U+0039 '9', or
4518 /// - U+0041 'A' ... U+0046 'F', or
4519 /// - U+0061 'a' ... U+0066 'f'.
4524 /// let uppercase_a = b'A';
4525 /// let uppercase_g = b'G';
4528 /// let zero = b'0';
4529 /// let percent = b'%';
4530 /// let space = b' ';
4532 /// let esc = 0x1b_u8;
4534 /// assert!(uppercase_a.is_ascii_hexdigit());
4535 /// assert!(!uppercase_g.is_ascii_hexdigit());
4536 /// assert!(a.is_ascii_hexdigit());
4537 /// assert!(!g.is_ascii_hexdigit());
4538 /// assert!(zero.is_ascii_hexdigit());
4539 /// assert!(!percent.is_ascii_hexdigit());
4540 /// assert!(!space.is_ascii_hexdigit());
4541 /// assert!(!lf.is_ascii_hexdigit());
4542 /// assert!(!esc.is_ascii_hexdigit());
4544 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4546 pub fn is_ascii_hexdigit(&self) -> bool {
4547 if *self >= 0x80 { return false }
4548 match ASCII_CHARACTER_CLASS[*self as usize] {
4549 D | Lx | Ux => true,
4554 /// Checks if the value is an ASCII punctuation character:
4556 /// - U+0021 ... U+002F `! " # $ % & ' ( ) * + , - . /`, or
4557 /// - U+003A ... U+0040 `: ; < = > ? @`, or
4558 /// - U+005B ... U+0060 ``[ \ ] ^ _ ` ``, or
4559 /// - U+007B ... U+007E `{ | } ~`
4564 /// let uppercase_a = b'A';
4565 /// let uppercase_g = b'G';
4568 /// let zero = b'0';
4569 /// let percent = b'%';
4570 /// let space = b' ';
4572 /// let esc = 0x1b_u8;
4574 /// assert!(!uppercase_a.is_ascii_punctuation());
4575 /// assert!(!uppercase_g.is_ascii_punctuation());
4576 /// assert!(!a.is_ascii_punctuation());
4577 /// assert!(!g.is_ascii_punctuation());
4578 /// assert!(!zero.is_ascii_punctuation());
4579 /// assert!(percent.is_ascii_punctuation());
4580 /// assert!(!space.is_ascii_punctuation());
4581 /// assert!(!lf.is_ascii_punctuation());
4582 /// assert!(!esc.is_ascii_punctuation());
4584 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4586 pub fn is_ascii_punctuation(&self) -> bool {
4587 if *self >= 0x80 { return false }
4588 match ASCII_CHARACTER_CLASS[*self as usize] {
4594 /// Checks if the value is an ASCII graphic character:
4595 /// U+0021 '!' ... U+007E '~'.
4600 /// let uppercase_a = b'A';
4601 /// let uppercase_g = b'G';
4604 /// let zero = b'0';
4605 /// let percent = b'%';
4606 /// let space = b' ';
4608 /// let esc = 0x1b_u8;
4610 /// assert!(uppercase_a.is_ascii_graphic());
4611 /// assert!(uppercase_g.is_ascii_graphic());
4612 /// assert!(a.is_ascii_graphic());
4613 /// assert!(g.is_ascii_graphic());
4614 /// assert!(zero.is_ascii_graphic());
4615 /// assert!(percent.is_ascii_graphic());
4616 /// assert!(!space.is_ascii_graphic());
4617 /// assert!(!lf.is_ascii_graphic());
4618 /// assert!(!esc.is_ascii_graphic());
4620 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4622 pub fn is_ascii_graphic(&self) -> bool {
4623 if *self >= 0x80 { return false; }
4624 match ASCII_CHARACTER_CLASS[*self as usize] {
4625 Ux | U | Lx | L | D | P => true,
4630 /// Checks if the value is an ASCII whitespace character:
4631 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
4632 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
4634 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
4635 /// whitespace][infra-aw]. There are several other definitions in
4636 /// wide use. For instance, [the POSIX locale][pct] includes
4637 /// U+000B VERTICAL TAB as well as all the above characters,
4638 /// but—from the very same specification—[the default rule for
4639 /// "field splitting" in the Bourne shell][bfs] considers *only*
4640 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
4642 /// If you are writing a program that will process an existing
4643 /// file format, check what that format's definition of whitespace is
4644 /// before using this function.
4646 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
4647 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
4648 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
4653 /// let uppercase_a = b'A';
4654 /// let uppercase_g = b'G';
4657 /// let zero = b'0';
4658 /// let percent = b'%';
4659 /// let space = b' ';
4661 /// let esc = 0x1b_u8;
4663 /// assert!(!uppercase_a.is_ascii_whitespace());
4664 /// assert!(!uppercase_g.is_ascii_whitespace());
4665 /// assert!(!a.is_ascii_whitespace());
4666 /// assert!(!g.is_ascii_whitespace());
4667 /// assert!(!zero.is_ascii_whitespace());
4668 /// assert!(!percent.is_ascii_whitespace());
4669 /// assert!(space.is_ascii_whitespace());
4670 /// assert!(lf.is_ascii_whitespace());
4671 /// assert!(!esc.is_ascii_whitespace());
4673 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4675 pub fn is_ascii_whitespace(&self) -> bool {
4676 if *self >= 0x80 { return false; }
4677 match ASCII_CHARACTER_CLASS[*self as usize] {
4683 /// Checks if the value is an ASCII control character:
4684 /// U+0000 NUL ... U+001F UNIT SEPARATOR, or U+007F DELETE.
4685 /// Note that most ASCII whitespace characters are control
4686 /// characters, but SPACE is not.
4691 /// let uppercase_a = b'A';
4692 /// let uppercase_g = b'G';
4695 /// let zero = b'0';
4696 /// let percent = b'%';
4697 /// let space = b' ';
4699 /// let esc = 0x1b_u8;
4701 /// assert!(!uppercase_a.is_ascii_control());
4702 /// assert!(!uppercase_g.is_ascii_control());
4703 /// assert!(!a.is_ascii_control());
4704 /// assert!(!g.is_ascii_control());
4705 /// assert!(!zero.is_ascii_control());
4706 /// assert!(!percent.is_ascii_control());
4707 /// assert!(!space.is_ascii_control());
4708 /// assert!(lf.is_ascii_control());
4709 /// assert!(esc.is_ascii_control());
4711 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4713 pub fn is_ascii_control(&self) -> bool {
4714 if *self >= 0x80 { return false; }
4715 match ASCII_CHARACTER_CLASS[*self as usize] {
4724 uint_impl! { u16, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4725 "[0x34, 0x12]", "[0x12, 0x34]" }
4730 uint_impl! { u32, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4731 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]" }
4736 uint_impl! { u64, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4737 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4738 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4739 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]" }
4744 uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "", 16,
4745 "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
4746 "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48",
4747 "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
4748 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4749 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
4750 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]" }
4753 #[cfg(target_pointer_width = "16")]
4756 uint_impl! { usize, u16, 16, 65536, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48",
4757 "[0x34, 0x12]", "[0x12, 0x34]" }
4759 #[cfg(target_pointer_width = "32")]
4762 uint_impl! { usize, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4763 "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]" }
4766 #[cfg(target_pointer_width = "64")]
4769 uint_impl! { usize, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4770 "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48",
4771 "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
4772 "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]" }
4775 /// A classification of floating point numbers.
4777 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
4778 /// their documentation for more.
4780 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
4781 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
4786 /// use std::num::FpCategory;
4789 /// let num = 12.4_f32;
4790 /// let inf = f32::INFINITY;
4791 /// let zero = 0f32;
4792 /// let sub: f32 = 1.1754942e-38;
4793 /// let nan = f32::NAN;
4795 /// assert_eq!(num.classify(), FpCategory::Normal);
4796 /// assert_eq!(inf.classify(), FpCategory::Infinite);
4797 /// assert_eq!(zero.classify(), FpCategory::Zero);
4798 /// assert_eq!(nan.classify(), FpCategory::Nan);
4799 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
4801 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
4802 #[stable(feature = "rust1", since = "1.0.0")]
4803 pub enum FpCategory {
4804 /// "Not a Number", often obtained by dividing by zero.
4805 #[stable(feature = "rust1", since = "1.0.0")]
4808 /// Positive or negative infinity.
4809 #[stable(feature = "rust1", since = "1.0.0")]
4812 /// Positive or negative zero.
4813 #[stable(feature = "rust1", since = "1.0.0")]
4816 /// De-normalized floating point representation (less precise than `Normal`).
4817 #[stable(feature = "rust1", since = "1.0.0")]
4820 /// A regular floating point number.
4821 #[stable(feature = "rust1", since = "1.0.0")]
4825 macro_rules! from_str_radix_int_impl {
4827 #[stable(feature = "rust1", since = "1.0.0")]
4828 impl FromStr for $t {
4829 type Err = ParseIntError;
4830 fn from_str(src: &str) -> Result<Self, ParseIntError> {
4831 from_str_radix(src, 10)
4836 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
4838 /// The error type returned when a checked integral type conversion fails.
4839 #[unstable(feature = "try_from", issue = "33417")]
4840 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
4841 pub struct TryFromIntError(());
4843 impl TryFromIntError {
4844 #[unstable(feature = "int_error_internals",
4845 reason = "available through Error trait and this method should \
4846 not be exposed publicly",
4849 pub fn __description(&self) -> &str {
4850 "out of range integral type conversion attempted"
4854 #[unstable(feature = "try_from", issue = "33417")]
4855 impl fmt::Display for TryFromIntError {
4856 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4857 self.__description().fmt(fmt)
4861 #[unstable(feature = "try_from", issue = "33417")]
4862 impl From<!> for TryFromIntError {
4863 fn from(never: !) -> TryFromIntError {
4868 // no possible bounds violation
4869 macro_rules! try_from_unbounded {
4870 ($source:ty, $($target:ty),*) => {$(
4871 #[unstable(feature = "try_from", issue = "33417")]
4872 impl TryFrom<$source> for $target {
4873 type Error = TryFromIntError;
4876 fn try_from(value: $source) -> Result<Self, Self::Error> {
4877 Ok(value as $target)
4883 // only negative bounds
4884 macro_rules! try_from_lower_bounded {
4885 ($source:ty, $($target:ty),*) => {$(
4886 #[unstable(feature = "try_from", issue = "33417")]
4887 impl TryFrom<$source> for $target {
4888 type Error = TryFromIntError;
4891 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4895 Err(TryFromIntError(()))
4902 // unsigned to signed (only positive bound)
4903 macro_rules! try_from_upper_bounded {
4904 ($source:ty, $($target:ty),*) => {$(
4905 #[unstable(feature = "try_from", issue = "33417")]
4906 impl TryFrom<$source> for $target {
4907 type Error = TryFromIntError;
4910 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4911 if u > (<$target>::max_value() as $source) {
4912 Err(TryFromIntError(()))
4922 macro_rules! try_from_both_bounded {
4923 ($source:ty, $($target:ty),*) => {$(
4924 #[unstable(feature = "try_from", issue = "33417")]
4925 impl TryFrom<$source> for $target {
4926 type Error = TryFromIntError;
4929 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4930 let min = <$target>::min_value() as $source;
4931 let max = <$target>::max_value() as $source;
4932 if u < min || u > max {
4933 Err(TryFromIntError(()))
4943 ($mac:ident, $source:ty, $($target:ty),*) => {$(
4944 $mac!($target, $source);
4948 /// intra-sign conversions
4949 try_from_upper_bounded!(u16, u8);
4950 try_from_upper_bounded!(u32, u16, u8);
4951 try_from_upper_bounded!(u64, u32, u16, u8);
4952 try_from_upper_bounded!(u128, u64, u32, u16, u8);
4954 try_from_both_bounded!(i16, i8);
4955 try_from_both_bounded!(i32, i16, i8);
4956 try_from_both_bounded!(i64, i32, i16, i8);
4957 try_from_both_bounded!(i128, i64, i32, i16, i8);
4959 // unsigned-to-signed
4960 try_from_upper_bounded!(u8, i8);
4961 try_from_upper_bounded!(u16, i8, i16);
4962 try_from_upper_bounded!(u32, i8, i16, i32);
4963 try_from_upper_bounded!(u64, i8, i16, i32, i64);
4964 try_from_upper_bounded!(u128, i8, i16, i32, i64, i128);
4966 // signed-to-unsigned
4967 try_from_lower_bounded!(i8, u8, u16, u32, u64, u128);
4968 try_from_lower_bounded!(i16, u16, u32, u64, u128);
4969 try_from_lower_bounded!(i32, u32, u64, u128);
4970 try_from_lower_bounded!(i64, u64, u128);
4971 try_from_lower_bounded!(i128, u128);
4972 try_from_both_bounded!(i16, u8);
4973 try_from_both_bounded!(i32, u16, u8);
4974 try_from_both_bounded!(i64, u32, u16, u8);
4975 try_from_both_bounded!(i128, u64, u32, u16, u8);
4978 try_from_upper_bounded!(usize, isize);
4979 try_from_lower_bounded!(isize, usize);
4981 #[cfg(target_pointer_width = "16")]
4982 mod ptr_try_from_impls {
4983 use super::TryFromIntError;
4984 use convert::TryFrom;
4986 try_from_upper_bounded!(usize, u8);
4987 try_from_unbounded!(usize, u16, u32, u64, u128);
4988 try_from_upper_bounded!(usize, i8, i16);
4989 try_from_unbounded!(usize, i32, i64, i128);
4991 try_from_both_bounded!(isize, u8);
4992 try_from_lower_bounded!(isize, u16, u32, u64, u128);
4993 try_from_both_bounded!(isize, i8);
4994 try_from_unbounded!(isize, i16, i32, i64, i128);
4996 rev!(try_from_upper_bounded, usize, u32, u64, u128);
4997 rev!(try_from_lower_bounded, usize, i8, i16);
4998 rev!(try_from_both_bounded, usize, i32, i64, i128);
5000 rev!(try_from_upper_bounded, isize, u16, u32, u64, u128);
5001 rev!(try_from_both_bounded, isize, i32, i64, i128);
5004 #[cfg(target_pointer_width = "32")]
5005 mod ptr_try_from_impls {
5006 use super::TryFromIntError;
5007 use convert::TryFrom;
5009 try_from_upper_bounded!(usize, u8, u16);
5010 try_from_unbounded!(usize, u32, u64, u128);
5011 try_from_upper_bounded!(usize, i8, i16, i32);
5012 try_from_unbounded!(usize, i64, i128);
5014 try_from_both_bounded!(isize, u8, u16);
5015 try_from_lower_bounded!(isize, u32, u64, u128);
5016 try_from_both_bounded!(isize, i8, i16);
5017 try_from_unbounded!(isize, i32, i64, i128);
5019 rev!(try_from_unbounded, usize, u32);
5020 rev!(try_from_upper_bounded, usize, u64, u128);
5021 rev!(try_from_lower_bounded, usize, i8, i16, i32);
5022 rev!(try_from_both_bounded, usize, i64, i128);
5024 rev!(try_from_unbounded, isize, u16);
5025 rev!(try_from_upper_bounded, isize, u32, u64, u128);
5026 rev!(try_from_unbounded, isize, i32);
5027 rev!(try_from_both_bounded, isize, i64, i128);
5030 #[cfg(target_pointer_width = "64")]
5031 mod ptr_try_from_impls {
5032 use super::TryFromIntError;
5033 use convert::TryFrom;
5035 try_from_upper_bounded!(usize, u8, u16, u32);
5036 try_from_unbounded!(usize, u64, u128);
5037 try_from_upper_bounded!(usize, i8, i16, i32, i64);
5038 try_from_unbounded!(usize, i128);
5040 try_from_both_bounded!(isize, u8, u16, u32);
5041 try_from_lower_bounded!(isize, u64, u128);
5042 try_from_both_bounded!(isize, i8, i16, i32);
5043 try_from_unbounded!(isize, i64, i128);
5045 rev!(try_from_unbounded, usize, u32, u64);
5046 rev!(try_from_upper_bounded, usize, u128);
5047 rev!(try_from_lower_bounded, usize, i8, i16, i32, i64);
5048 rev!(try_from_both_bounded, usize, i128);
5050 rev!(try_from_unbounded, isize, u16, u32);
5051 rev!(try_from_upper_bounded, isize, u64, u128);
5052 rev!(try_from_unbounded, isize, i32, i64);
5053 rev!(try_from_both_bounded, isize, i128);
5057 trait FromStrRadixHelper: PartialOrd + Copy {
5058 fn min_value() -> Self;
5059 fn max_value() -> Self;
5060 fn from_u32(u: u32) -> Self;
5061 fn checked_mul(&self, other: u32) -> Option<Self>;
5062 fn checked_sub(&self, other: u32) -> Option<Self>;
5063 fn checked_add(&self, other: u32) -> Option<Self>;
5067 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
5069 fn min_value() -> Self { Self::min_value() }
5071 fn max_value() -> Self { Self::max_value() }
5073 fn from_u32(u: u32) -> Self { u as Self }
5075 fn checked_mul(&self, other: u32) -> Option<Self> {
5076 Self::checked_mul(*self, other as Self)
5079 fn checked_sub(&self, other: u32) -> Option<Self> {
5080 Self::checked_sub(*self, other as Self)
5083 fn checked_add(&self, other: u32) -> Option<Self> {
5084 Self::checked_add(*self, other as Self)
5088 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
5090 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
5091 use self::IntErrorKind::*;
5092 use self::ParseIntError as PIE;
5094 assert!(radix >= 2 && radix <= 36,
5095 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
5099 return Err(PIE { kind: Empty });
5102 let is_signed_ty = T::from_u32(0) > T::min_value();
5104 // all valid digits are ascii, so we will just iterate over the utf8 bytes
5105 // and cast them to chars. .to_digit() will safely return None for anything
5106 // other than a valid ascii digit for the given radix, including the first-byte
5107 // of multi-byte sequences
5108 let src = src.as_bytes();
5110 let (is_positive, digits) = match src[0] {
5111 b'+' => (true, &src[1..]),
5112 b'-' if is_signed_ty => (false, &src[1..]),
5116 if digits.is_empty() {
5117 return Err(PIE { kind: Empty });
5120 let mut result = T::from_u32(0);
5122 // The number is positive
5124 let x = match (c as char).to_digit(radix) {
5126 None => return Err(PIE { kind: InvalidDigit }),
5128 result = match result.checked_mul(radix) {
5129 Some(result) => result,
5130 None => return Err(PIE { kind: Overflow }),
5132 result = match result.checked_add(x) {
5133 Some(result) => result,
5134 None => return Err(PIE { kind: Overflow }),
5138 // The number is negative
5140 let x = match (c as char).to_digit(radix) {
5142 None => return Err(PIE { kind: InvalidDigit }),
5144 result = match result.checked_mul(radix) {
5145 Some(result) => result,
5146 None => return Err(PIE { kind: Underflow }),
5148 result = match result.checked_sub(x) {
5149 Some(result) => result,
5150 None => return Err(PIE { kind: Underflow }),
5157 /// An error which can be returned when parsing an integer.
5159 /// This error is used as the error type for the `from_str_radix()` functions
5160 /// on the primitive integer types, such as [`i8::from_str_radix`].
5162 /// # Potential causes
5164 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
5165 /// in the string e.g. when it is obtained from the standard input.
5166 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
5168 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
5169 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
5170 #[derive(Debug, Clone, PartialEq, Eq)]
5171 #[stable(feature = "rust1", since = "1.0.0")]
5172 pub struct ParseIntError {
5176 #[derive(Debug, Clone, PartialEq, Eq)]
5184 impl ParseIntError {
5185 #[unstable(feature = "int_error_internals",
5186 reason = "available through Error trait and this method should \
5187 not be exposed publicly",
5190 pub fn __description(&self) -> &str {
5192 IntErrorKind::Empty => "cannot parse integer from empty string",
5193 IntErrorKind::InvalidDigit => "invalid digit found in string",
5194 IntErrorKind::Overflow => "number too large to fit in target type",
5195 IntErrorKind::Underflow => "number too small to fit in target type",
5200 #[stable(feature = "rust1", since = "1.0.0")]
5201 impl fmt::Display for ParseIntError {
5202 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5203 self.__description().fmt(f)
5207 #[stable(feature = "rust1", since = "1.0.0")]
5208 pub use num::dec2flt::ParseFloatError;
5210 // Conversion traits for primitive integer and float types
5211 // Conversions T -> T are covered by a blanket impl and therefore excluded
5212 // Some conversions from and to usize/isize are not implemented due to portability concerns
5213 macro_rules! impl_from {
5214 ($Small: ty, $Large: ty, #[$attr:meta], $doc: expr) => {
5217 impl From<$Small> for $Large {
5219 fn from(small: $Small) -> $Large {
5224 ($Small: ty, $Large: ty, #[$attr:meta]) => {
5228 concat!("Converts `",
5236 macro_rules! impl_from_bool {
5237 ($target: ty, #[$attr:meta]) => {
5238 impl_from!(bool, $target, #[$attr], concat!("Converts a `bool` to a `",
5239 stringify!($target), "`. The resulting value is `0` for `false` and `1` for `true`
5245 assert_eq!(", stringify!($target), "::from(true), 1);
5246 assert_eq!(", stringify!($target), "::from(false), 0);
5252 impl_from_bool! { u8, #[stable(feature = "from_bool", since = "1.28.0")] }
5253 impl_from_bool! { u16, #[stable(feature = "from_bool", since = "1.28.0")] }
5254 impl_from_bool! { u32, #[stable(feature = "from_bool", since = "1.28.0")] }
5255 impl_from_bool! { u64, #[stable(feature = "from_bool", since = "1.28.0")] }
5256 impl_from_bool! { u128, #[stable(feature = "from_bool", since = "1.28.0")] }
5257 impl_from_bool! { usize, #[stable(feature = "from_bool", since = "1.28.0")] }
5258 impl_from_bool! { i8, #[stable(feature = "from_bool", since = "1.28.0")] }
5259 impl_from_bool! { i16, #[stable(feature = "from_bool", since = "1.28.0")] }
5260 impl_from_bool! { i32, #[stable(feature = "from_bool", since = "1.28.0")] }
5261 impl_from_bool! { i64, #[stable(feature = "from_bool", since = "1.28.0")] }
5262 impl_from_bool! { i128, #[stable(feature = "from_bool", since = "1.28.0")] }
5263 impl_from_bool! { isize, #[stable(feature = "from_bool", since = "1.28.0")] }
5265 // Unsigned -> Unsigned
5266 impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5267 impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5268 impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5269 impl_from! { u8, u128, #[stable(feature = "i128", since = "1.26.0")] }
5270 impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5271 impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5272 impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5273 impl_from! { u16, u128, #[stable(feature = "i128", since = "1.26.0")] }
5274 impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5275 impl_from! { u32, u128, #[stable(feature = "i128", since = "1.26.0")] }
5276 impl_from! { u64, u128, #[stable(feature = "i128", since = "1.26.0")] }
5279 impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5280 impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5281 impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5282 impl_from! { i8, i128, #[stable(feature = "i128", since = "1.26.0")] }
5283 impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5284 impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5285 impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5286 impl_from! { i16, i128, #[stable(feature = "i128", since = "1.26.0")] }
5287 impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5288 impl_from! { i32, i128, #[stable(feature = "i128", since = "1.26.0")] }
5289 impl_from! { i64, i128, #[stable(feature = "i128", since = "1.26.0")] }
5291 // Unsigned -> Signed
5292 impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5293 impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5294 impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5295 impl_from! { u8, i128, #[stable(feature = "i128", since = "1.26.0")] }
5296 impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5297 impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5298 impl_from! { u16, i128, #[stable(feature = "i128", since = "1.26.0")] }
5299 impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
5300 impl_from! { u32, i128, #[stable(feature = "i128", since = "1.26.0")] }
5301 impl_from! { u64, i128, #[stable(feature = "i128", since = "1.26.0")] }
5303 // The C99 standard defines bounds on INTPTR_MIN, INTPTR_MAX, and UINTPTR_MAX
5304 // which imply that pointer-sized integers must be at least 16 bits:
5305 // https://port70.net/~nsz/c/c99/n1256.html#7.18.2.4
5306 impl_from! { u16, usize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
5307 impl_from! { u8, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
5308 impl_from! { i16, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
5310 // RISC-V defines the possibility of a 128-bit address space (RV128).
5312 // CHERI proposes 256-bit “capabilities”. Unclear if this would be relevant to usize/isize.
5313 // https://www.cl.cam.ac.uk/research/security/ctsrd/pdfs/20171017a-cheri-poster.pdf
5314 // http://www.csl.sri.com/users/neumann/2012resolve-cheri.pdf
5317 // Note: integers can only be represented with full precision in a float if
5318 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
5319 // Lossy float conversions are not implemented at this time.
5322 impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5323 impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5324 impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5325 impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5326 impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5328 // Unsigned -> Float
5329 impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5330 impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5331 impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5332 impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5333 impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5336 impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
5338 static ASCII_LOWERCASE_MAP: [u8; 256] = [
5339 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
5340 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
5341 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
5342 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
5343 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
5344 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
5345 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
5346 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
5349 b'a', b'b', b'c', b'd', b'e', b'f', b'g',
5350 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
5351 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
5354 b'[', b'\\', b']', b'^', b'_',
5355 b'`', b'a', b'b', b'c', b'd', b'e', b'f', b'g',
5356 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
5357 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
5358 b'x', b'y', b'z', b'{', b'|', b'}', b'~', 0x7f,
5359 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
5360 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
5361 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
5362 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
5363 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
5364 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
5365 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
5366 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
5367 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
5368 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
5369 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
5370 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
5371 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
5372 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
5373 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
5374 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
5377 static ASCII_UPPERCASE_MAP: [u8; 256] = [
5378 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
5379 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
5380 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
5381 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
5382 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
5383 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
5384 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
5385 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
5386 b'@', b'A', b'B', b'C', b'D', b'E', b'F', b'G',
5387 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
5388 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
5389 b'X', b'Y', b'Z', b'[', b'\\', b']', b'^', b'_',
5392 b'A', b'B', b'C', b'D', b'E', b'F', b'G',
5393 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
5394 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
5397 b'{', b'|', b'}', b'~', 0x7f,
5398 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
5399 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
5400 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
5401 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
5402 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
5403 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
5404 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
5405 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
5406 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
5407 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
5408 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
5409 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
5410 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
5411 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
5412 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
5413 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
5416 enum AsciiCharacterClass {
5418 Cw, // control whitespace
5422 Lx, // lowercase hex digit
5424 Ux, // uppercase hex digit
5427 use self::AsciiCharacterClass::*;
5429 static ASCII_CHARACTER_CLASS: [AsciiCharacterClass; 128] = [
5430 // _0 _1 _2 _3 _4 _5 _6 _7 _8 _9 _a _b _c _d _e _f
5431 C, C, C, C, C, C, C, C, C, Cw,Cw,C, Cw,Cw,C, C, // 0_
5432 C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, // 1_
5433 W, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, // 2_
5434 D, D, D, D, D, D, D, D, D, D, P, P, P, P, P, P, // 3_
5435 P, Ux,Ux,Ux,Ux,Ux,Ux,U, U, U, U, U, U, U, U, U, // 4_
5436 U, U, U, U, U, U, U, U, U, U, U, P, P, P, P, P, // 5_
5437 P, Lx,Lx,Lx,Lx,Lx,Lx,L, L, L, L, L, L, L, L, L, // 6_
5438 L, L, L, L, L, L, L, L, L, L, L, P, P, P, P, C, // 7_