1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Numeric traits and functions for the built-in numeric types.
13 #![stable(feature = "rust1", since = "1.0.0")]
15 use convert
::{Infallible, TryFrom}
;
21 /// Provides intentionally-wrapped arithmetic on `T`.
23 /// Operations like `+` on `u32` values is intended to never overflow,
24 /// and in some debug configurations overflow is detected and results
25 /// in a panic. While most arithmetic falls into this category, some
26 /// code explicitly expects and relies upon modular arithmetic (e.g.,
29 /// Wrapping arithmetic can be achieved either through methods like
30 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
31 /// all standard arithmetic operations on the underlying value are
32 /// intended to have wrapping semantics.
37 /// use std::num::Wrapping;
39 /// let zero = Wrapping(0u32);
40 /// let one = Wrapping(1u32);
42 /// assert_eq!(std::u32::MAX, (zero - one).0);
44 #[stable(feature = "rust1", since = "1.0.0")]
45 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
46 pub struct Wrapping
<T
>(#[stable(feature = "rust1", since = "1.0.0")]
49 #[stable(feature = "rust1", since = "1.0.0")]
50 impl<T
: fmt
::Debug
> fmt
::Debug
for Wrapping
<T
> {
51 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
56 #[stable(feature = "wrapping_display", since = "1.10.0")]
57 impl<T
: fmt
::Display
> fmt
::Display
for Wrapping
<T
> {
58 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
63 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
64 impl<T
: fmt
::Binary
> fmt
::Binary
for Wrapping
<T
> {
65 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
70 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
71 impl<T
: fmt
::Octal
> fmt
::Octal
for Wrapping
<T
> {
72 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
77 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
78 impl<T
: fmt
::LowerHex
> fmt
::LowerHex
for Wrapping
<T
> {
79 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
84 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
85 impl<T
: fmt
::UpperHex
> fmt
::UpperHex
for Wrapping
<T
> {
86 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
93 // All these modules are technically private and only exposed for coretests:
99 // `Int` + `SignedInt` implemented for signed integers
100 macro_rules
! int_impl
{
101 ($SelfT
:ty
, $ActualT
:ident
, $UnsignedT
:ty
, $BITS
:expr
) => {
102 /// Returns the smallest value that can be represented by this integer type.
109 /// assert_eq!(i8::min_value(), -128);
111 #[stable(feature = "rust1", since = "1.0.0")]
113 pub const fn min_value() -> Self {
114 !0 ^
((!0 as $UnsignedT
) >> 1) as Self
117 /// Returns the largest value that can be represented by this integer type.
124 /// assert_eq!(i8::max_value(), 127);
126 #[stable(feature = "rust1", since = "1.0.0")]
128 pub const fn max_value() -> Self {
132 /// Converts a string slice in a given base to an integer.
134 /// The string is expected to be an optional `+` or `-` sign
135 /// followed by digits.
136 /// Leading and trailing whitespace represent an error.
137 /// Digits are a subset of these characters, depending on `radix`:
145 /// This function panics if `radix` is not in the range from 2 to 36.
152 /// assert_eq!(i32::from_str_radix("A", 16), Ok(10));
154 #[stable(feature = "rust1", since = "1.0.0")]
155 pub fn from_str_radix(src
: &str, radix
: u32) -> Result
<Self, ParseIntError
> {
156 from_str_radix(src
, radix
)
159 /// Returns the number of ones in the binary representation of `self`.
166 /// let n = -0b1000_0000i8;
168 /// assert_eq!(n.count_ones(), 1);
170 #[stable(feature = "rust1", since = "1.0.0")]
172 pub fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
174 /// Returns the number of zeros in the binary representation of `self`.
181 /// let n = -0b1000_0000i8;
183 /// assert_eq!(n.count_zeros(), 7);
185 #[stable(feature = "rust1", since = "1.0.0")]
187 pub fn count_zeros(self) -> u32 {
191 /// Returns the number of leading zeros in the binary representation
201 /// assert_eq!(n.leading_zeros(), 0);
203 #[stable(feature = "rust1", since = "1.0.0")]
205 pub fn leading_zeros(self) -> u32 {
206 (self as $UnsignedT
).leading_zeros()
209 /// Returns the number of trailing zeros in the binary representation
219 /// assert_eq!(n.trailing_zeros(), 2);
221 #[stable(feature = "rust1", since = "1.0.0")]
223 pub fn trailing_zeros(self) -> u32 {
224 (self as $UnsignedT
).trailing_zeros()
227 /// Shifts the bits to the left by a specified amount, `n`,
228 /// wrapping the truncated bits to the end of the resulting integer.
230 /// Please note this isn't the same operation as `<<`!
237 /// let n = 0x0123456789ABCDEFi64;
238 /// let m = -0x76543210FEDCBA99i64;
240 /// assert_eq!(n.rotate_left(32), m);
242 #[stable(feature = "rust1", since = "1.0.0")]
244 pub fn rotate_left(self, n
: u32) -> Self {
245 (self as $UnsignedT
).rotate_left(n
) as Self
248 /// Shifts the bits to the right by a specified amount, `n`,
249 /// wrapping the truncated bits to the beginning of the resulting
252 /// Please note this isn't the same operation as `>>`!
259 /// let n = 0x0123456789ABCDEFi64;
260 /// let m = -0xFEDCBA987654322i64;
262 /// assert_eq!(n.rotate_right(4), m);
264 #[stable(feature = "rust1", since = "1.0.0")]
266 pub fn rotate_right(self, n
: u32) -> Self {
267 (self as $UnsignedT
).rotate_right(n
) as Self
270 /// Reverses the byte order of the integer.
277 /// let n: i16 = 0b0000000_01010101;
278 /// assert_eq!(n, 85);
280 /// let m = n.swap_bytes();
282 /// assert_eq!(m, 0b01010101_00000000);
283 /// assert_eq!(m, 21760);
285 #[stable(feature = "rust1", since = "1.0.0")]
287 pub fn swap_bytes(self) -> Self {
288 (self as $UnsignedT
).swap_bytes() as Self
291 /// Converts an integer from big endian to the target's endianness.
293 /// On big endian this is a no-op. On little endian the bytes are
301 /// let n = 0x0123456789ABCDEFi64;
303 /// if cfg!(target_endian = "big") {
304 /// assert_eq!(i64::from_be(n), n)
306 /// assert_eq!(i64::from_be(n), n.swap_bytes())
309 #[stable(feature = "rust1", since = "1.0.0")]
311 pub fn from_be(x
: Self) -> Self {
312 if cfg
!(target_endian
= "big") { x }
else { x.swap_bytes() }
315 /// Converts an integer from little endian to the target's endianness.
317 /// On little endian this is a no-op. On big endian the bytes are
325 /// let n = 0x0123456789ABCDEFi64;
327 /// if cfg!(target_endian = "little") {
328 /// assert_eq!(i64::from_le(n), n)
330 /// assert_eq!(i64::from_le(n), n.swap_bytes())
333 #[stable(feature = "rust1", since = "1.0.0")]
335 pub fn from_le(x
: Self) -> Self {
336 if cfg
!(target_endian
= "little") { x }
else { x.swap_bytes() }
339 /// Converts `self` to big endian from the target's endianness.
341 /// On big endian this is a no-op. On little endian the bytes are
349 /// let n = 0x0123456789ABCDEFi64;
351 /// if cfg!(target_endian = "big") {
352 /// assert_eq!(n.to_be(), n)
354 /// assert_eq!(n.to_be(), n.swap_bytes())
357 #[stable(feature = "rust1", since = "1.0.0")]
359 pub fn to_be(self) -> Self { // or not to be?
360 if cfg
!(target_endian
= "big") { self }
else { self.swap_bytes() }
363 /// Converts `self` to little endian from the target's endianness.
365 /// On little endian this is a no-op. On big endian the bytes are
373 /// let n = 0x0123456789ABCDEFi64;
375 /// if cfg!(target_endian = "little") {
376 /// assert_eq!(n.to_le(), n)
378 /// assert_eq!(n.to_le(), n.swap_bytes())
381 #[stable(feature = "rust1", since = "1.0.0")]
383 pub fn to_le(self) -> Self {
384 if cfg
!(target_endian
= "little") { self }
else { self.swap_bytes() }
387 /// Checked integer addition. Computes `self + rhs`, returning `None`
388 /// if overflow occurred.
395 /// assert_eq!(7i16.checked_add(32760), Some(32767));
396 /// assert_eq!(8i16.checked_add(32760), None);
398 #[stable(feature = "rust1", since = "1.0.0")]
400 pub fn checked_add(self, rhs
: Self) -> Option
<Self> {
401 let (a
, b
) = self.overflowing_add(rhs
);
402 if b {None}
else {Some(a)}
405 /// Checked integer subtraction. Computes `self - rhs`, returning
406 /// `None` if overflow occurred.
413 /// assert_eq!((-127i8).checked_sub(1), Some(-128));
414 /// assert_eq!((-128i8).checked_sub(1), None);
416 #[stable(feature = "rust1", since = "1.0.0")]
418 pub fn checked_sub(self, rhs
: Self) -> Option
<Self> {
419 let (a
, b
) = self.overflowing_sub(rhs
);
420 if b {None}
else {Some(a)}
423 /// Checked integer multiplication. Computes `self * rhs`, returning
424 /// `None` if overflow occurred.
431 /// assert_eq!(6i8.checked_mul(21), Some(126));
432 /// assert_eq!(6i8.checked_mul(22), None);
434 #[stable(feature = "rust1", since = "1.0.0")]
436 pub fn checked_mul(self, rhs
: Self) -> Option
<Self> {
437 let (a
, b
) = self.overflowing_mul(rhs
);
438 if b {None}
else {Some(a)}
441 /// Checked integer division. Computes `self / rhs`, returning `None`
442 /// if `rhs == 0` or the division results in overflow.
449 /// assert_eq!((-127i8).checked_div(-1), Some(127));
450 /// assert_eq!((-128i8).checked_div(-1), None);
451 /// assert_eq!((1i8).checked_div(0), None);
453 #[stable(feature = "rust1", since = "1.0.0")]
455 pub fn checked_div(self, rhs
: Self) -> Option
<Self> {
456 if rhs
== 0 || (self == Self::min_value() && rhs
== -1) {
459 Some(unsafe { intrinsics::unchecked_div(self, rhs) }
)
463 /// Checked integer remainder. Computes `self % rhs`, returning `None`
464 /// if `rhs == 0` or the division results in overflow.
473 /// assert_eq!(5i32.checked_rem(2), Some(1));
474 /// assert_eq!(5i32.checked_rem(0), None);
475 /// assert_eq!(i32::MIN.checked_rem(-1), None);
477 #[stable(feature = "wrapping", since = "1.7.0")]
479 pub fn checked_rem(self, rhs
: Self) -> Option
<Self> {
480 if rhs
== 0 || (self == Self::min_value() && rhs
== -1) {
483 Some(unsafe { intrinsics::unchecked_rem(self, rhs) }
)
487 /// Checked negation. Computes `-self`, returning `None` if `self ==
497 /// assert_eq!(5i32.checked_neg(), Some(-5));
498 /// assert_eq!(i32::MIN.checked_neg(), None);
500 #[stable(feature = "wrapping", since = "1.7.0")]
502 pub fn checked_neg(self) -> Option
<Self> {
503 let (a
, b
) = self.overflowing_neg();
504 if b {None}
else {Some(a)}
507 /// Checked shift left. Computes `self << rhs`, returning `None`
508 /// if `rhs` is larger than or equal to the number of bits in `self`.
515 /// assert_eq!(0x10i32.checked_shl(4), Some(0x100));
516 /// assert_eq!(0x10i32.checked_shl(33), None);
518 #[stable(feature = "wrapping", since = "1.7.0")]
520 pub fn checked_shl(self, rhs
: u32) -> Option
<Self> {
521 let (a
, b
) = self.overflowing_shl(rhs
);
522 if b {None}
else {Some(a)}
525 /// Checked shift right. Computes `self >> rhs`, returning `None`
526 /// if `rhs` is larger than or equal to the number of bits in `self`.
533 /// assert_eq!(0x10i32.checked_shr(4), Some(0x1));
534 /// assert_eq!(0x10i32.checked_shr(33), None);
536 #[stable(feature = "wrapping", since = "1.7.0")]
538 pub fn checked_shr(self, rhs
: u32) -> Option
<Self> {
539 let (a
, b
) = self.overflowing_shr(rhs
);
540 if b {None}
else {Some(a)}
543 /// Checked absolute value. Computes `self.abs()`, returning `None` if
553 /// assert_eq!((-5i32).checked_abs(), Some(5));
554 /// assert_eq!(i32::MIN.checked_abs(), None);
556 #[stable(feature = "no_panic_abs", since = "1.13.0")]
558 pub fn checked_abs(self) -> Option
<Self> {
559 if self.is_negative() {
566 /// Saturating integer addition. Computes `self + rhs`, saturating at
567 /// the numeric bounds instead of overflowing.
574 /// assert_eq!(100i8.saturating_add(1), 101);
575 /// assert_eq!(100i8.saturating_add(127), 127);
577 #[stable(feature = "rust1", since = "1.0.0")]
579 pub fn saturating_add(self, rhs
: Self) -> Self {
580 match self.checked_add(rhs
) {
582 None
if rhs
>= 0 => Self::max_value(),
583 None
=> Self::min_value(),
587 /// Saturating integer subtraction. Computes `self - rhs`, saturating
588 /// at the numeric bounds instead of overflowing.
595 /// assert_eq!(100i8.saturating_sub(127), -27);
596 /// assert_eq!((-100i8).saturating_sub(127), -128);
598 #[stable(feature = "rust1", since = "1.0.0")]
600 pub fn saturating_sub(self, rhs
: Self) -> Self {
601 match self.checked_sub(rhs
) {
603 None
if rhs
>= 0 => Self::min_value(),
604 None
=> Self::max_value(),
608 /// Saturating integer multiplication. Computes `self * rhs`,
609 /// saturating at the numeric bounds instead of overflowing.
618 /// assert_eq!(100i32.saturating_mul(127), 12700);
619 /// assert_eq!((1i32 << 23).saturating_mul(1 << 23), i32::MAX);
620 /// assert_eq!((-1i32 << 23).saturating_mul(1 << 23), i32::MIN);
622 #[stable(feature = "wrapping", since = "1.7.0")]
624 pub fn saturating_mul(self, rhs
: Self) -> Self {
625 self.checked_mul(rhs
).unwrap_or_else(|| {
626 if (self < 0 && rhs
< 0) || (self > 0 && rhs
> 0) {
634 /// Wrapping (modular) addition. Computes `self + rhs`,
635 /// wrapping around at the boundary of the type.
642 /// assert_eq!(100i8.wrapping_add(27), 127);
643 /// assert_eq!(100i8.wrapping_add(127), -29);
645 #[stable(feature = "rust1", since = "1.0.0")]
647 pub fn wrapping_add(self, rhs
: Self) -> Self {
649 intrinsics
::overflowing_add(self, rhs
)
653 /// Wrapping (modular) subtraction. Computes `self - rhs`,
654 /// wrapping around at the boundary of the type.
661 /// assert_eq!(0i8.wrapping_sub(127), -127);
662 /// assert_eq!((-2i8).wrapping_sub(127), 127);
664 #[stable(feature = "rust1", since = "1.0.0")]
666 pub fn wrapping_sub(self, rhs
: Self) -> Self {
668 intrinsics
::overflowing_sub(self, rhs
)
672 /// Wrapping (modular) multiplication. Computes `self *
673 /// rhs`, wrapping around at the boundary of the type.
680 /// assert_eq!(10i8.wrapping_mul(12), 120);
681 /// assert_eq!(11i8.wrapping_mul(12), -124);
683 #[stable(feature = "rust1", since = "1.0.0")]
685 pub fn wrapping_mul(self, rhs
: Self) -> Self {
687 intrinsics
::overflowing_mul(self, rhs
)
691 /// Wrapping (modular) division. Computes `self / rhs`,
692 /// wrapping around at the boundary of the type.
694 /// The only case where such wrapping can occur is when one
695 /// divides `MIN / -1` on a signed type (where `MIN` is the
696 /// negative minimal value for the type); this is equivalent
697 /// to `-MIN`, a positive value that is too large to represent
698 /// in the type. In such a case, this function returns `MIN`
703 /// This function will panic if `rhs` is 0.
710 /// assert_eq!(100u8.wrapping_div(10), 10);
711 /// assert_eq!((-128i8).wrapping_div(-1), -128);
713 #[stable(feature = "num_wrapping", since = "1.2.0")]
715 pub fn wrapping_div(self, rhs
: Self) -> Self {
716 self.overflowing_div(rhs
).0
719 /// Wrapping (modular) remainder. Computes `self % rhs`,
720 /// wrapping around at the boundary of the type.
722 /// Such wrap-around never actually occurs mathematically;
723 /// implementation artifacts make `x % y` invalid for `MIN /
724 /// -1` on a signed type (where `MIN` is the negative
725 /// minimal value). In such a case, this function returns `0`.
729 /// This function will panic if `rhs` is 0.
736 /// assert_eq!(100i8.wrapping_rem(10), 0);
737 /// assert_eq!((-128i8).wrapping_rem(-1), 0);
739 #[stable(feature = "num_wrapping", since = "1.2.0")]
741 pub fn wrapping_rem(self, rhs
: Self) -> Self {
742 self.overflowing_rem(rhs
).0
745 /// Wrapping (modular) negation. Computes `-self`,
746 /// wrapping around at the boundary of the type.
748 /// The only case where such wrapping can occur is when one
749 /// negates `MIN` on a signed type (where `MIN` is the
750 /// negative minimal value for the type); this is a positive
751 /// value that is too large to represent in the type. In such
752 /// a case, this function returns `MIN` itself.
759 /// assert_eq!(100i8.wrapping_neg(), -100);
760 /// assert_eq!((-128i8).wrapping_neg(), -128);
762 #[stable(feature = "num_wrapping", since = "1.2.0")]
764 pub fn wrapping_neg(self) -> Self {
765 self.overflowing_neg().0
768 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
769 /// where `mask` removes any high-order bits of `rhs` that
770 /// would cause the shift to exceed the bitwidth of the type.
772 /// Note that this is *not* the same as a rotate-left; the
773 /// RHS of a wrapping shift-left is restricted to the range
774 /// of the type, rather than the bits shifted out of the LHS
775 /// being returned to the other end. The primitive integer
776 /// types all implement a `rotate_left` function, which may
777 /// be what you want instead.
784 /// assert_eq!((-1i8).wrapping_shl(7), -128);
785 /// assert_eq!((-1i8).wrapping_shl(8), -1);
787 #[stable(feature = "num_wrapping", since = "1.2.0")]
789 pub fn wrapping_shl(self, rhs
: u32) -> Self {
791 intrinsics
::unchecked_shl(self, (rhs
& ($BITS
- 1)) as $SelfT
)
795 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
796 /// where `mask` removes any high-order bits of `rhs` that
797 /// would cause the shift to exceed the bitwidth of the type.
799 /// Note that this is *not* the same as a rotate-right; the
800 /// RHS of a wrapping shift-right is restricted to the range
801 /// of the type, rather than the bits shifted out of the LHS
802 /// being returned to the other end. The primitive integer
803 /// types all implement a `rotate_right` function, which may
804 /// be what you want instead.
811 /// assert_eq!((-128i8).wrapping_shr(7), -1);
812 /// assert_eq!((-128i8).wrapping_shr(8), -128);
814 #[stable(feature = "num_wrapping", since = "1.2.0")]
816 pub fn wrapping_shr(self, rhs
: u32) -> Self {
818 intrinsics
::unchecked_shr(self, (rhs
& ($BITS
- 1)) as $SelfT
)
822 /// Wrapping (modular) absolute value. Computes `self.abs()`,
823 /// wrapping around at the boundary of the type.
825 /// The only case where such wrapping can occur is when one takes
826 /// the absolute value of the negative minimal value for the type
827 /// this is a positive value that is too large to represent in the
828 /// type. In such a case, this function returns `MIN` itself.
835 /// assert_eq!(100i8.wrapping_abs(), 100);
836 /// assert_eq!((-100i8).wrapping_abs(), 100);
837 /// assert_eq!((-128i8).wrapping_abs(), -128);
838 /// assert_eq!((-128i8).wrapping_abs() as u8, 128);
840 #[stable(feature = "no_panic_abs", since = "1.13.0")]
842 pub fn wrapping_abs(self) -> Self {
843 if self.is_negative() {
850 /// Calculates `self` + `rhs`
852 /// Returns a tuple of the addition along with a boolean indicating
853 /// whether an arithmetic overflow would occur. If an overflow would
854 /// have occurred then the wrapped value is returned.
863 /// assert_eq!(5i32.overflowing_add(2), (7, false));
864 /// assert_eq!(i32::MAX.overflowing_add(1), (i32::MIN, true));
867 #[stable(feature = "wrapping", since = "1.7.0")]
868 pub fn overflowing_add(self, rhs
: Self) -> (Self, bool
) {
869 let (a
, b
) = unsafe {
870 intrinsics
::add_with_overflow(self as $ActualT
,
876 /// Calculates `self` - `rhs`
878 /// Returns a tuple of the subtraction along with a boolean indicating
879 /// whether an arithmetic overflow would occur. If an overflow would
880 /// have occurred then the wrapped value is returned.
889 /// assert_eq!(5i32.overflowing_sub(2), (3, false));
890 /// assert_eq!(i32::MIN.overflowing_sub(1), (i32::MAX, true));
893 #[stable(feature = "wrapping", since = "1.7.0")]
894 pub fn overflowing_sub(self, rhs
: Self) -> (Self, bool
) {
895 let (a
, b
) = unsafe {
896 intrinsics
::sub_with_overflow(self as $ActualT
,
902 /// Calculates the multiplication of `self` and `rhs`.
904 /// Returns a tuple of the multiplication along with a boolean
905 /// indicating whether an arithmetic overflow would occur. If an
906 /// overflow would have occurred then the wrapped value is returned.
913 /// assert_eq!(5i32.overflowing_mul(2), (10, false));
914 /// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
917 #[stable(feature = "wrapping", since = "1.7.0")]
918 pub fn overflowing_mul(self, rhs
: Self) -> (Self, bool
) {
919 let (a
, b
) = unsafe {
920 intrinsics
::mul_with_overflow(self as $ActualT
,
926 /// Calculates the divisor when `self` is divided by `rhs`.
928 /// Returns a tuple of the divisor along with a boolean indicating
929 /// whether an arithmetic overflow would occur. If an overflow would
930 /// occur then self is returned.
934 /// This function will panic if `rhs` is 0.
943 /// assert_eq!(5i32.overflowing_div(2), (2, false));
944 /// assert_eq!(i32::MIN.overflowing_div(-1), (i32::MIN, true));
947 #[stable(feature = "wrapping", since = "1.7.0")]
948 pub fn overflowing_div(self, rhs
: Self) -> (Self, bool
) {
949 if self == Self::min_value() && rhs
== -1 {
956 /// Calculates the remainder when `self` is divided by `rhs`.
958 /// Returns a tuple of the remainder after dividing along with a boolean
959 /// indicating whether an arithmetic overflow would occur. If an
960 /// overflow would occur then 0 is returned.
964 /// This function will panic if `rhs` is 0.
973 /// assert_eq!(5i32.overflowing_rem(2), (1, false));
974 /// assert_eq!(i32::MIN.overflowing_rem(-1), (0, true));
977 #[stable(feature = "wrapping", since = "1.7.0")]
978 pub fn overflowing_rem(self, rhs
: Self) -> (Self, bool
) {
979 if self == Self::min_value() && rhs
== -1 {
986 /// Negates self, overflowing if this is equal to the minimum value.
988 /// Returns a tuple of the negated version of self along with a boolean
989 /// indicating whether an overflow happened. If `self` is the minimum
990 /// value (e.g. `i32::MIN` for values of type `i32`), then the minimum
991 /// value will be returned again and `true` will be returned for an
992 /// overflow happening.
1001 /// assert_eq!(2i32.overflowing_neg(), (-2, false));
1002 /// assert_eq!(i32::MIN.overflowing_neg(), (i32::MIN, true));
1005 #[stable(feature = "wrapping", since = "1.7.0")]
1006 pub fn overflowing_neg(self) -> (Self, bool
) {
1007 if self == Self::min_value() {
1008 (Self::min_value(), true)
1014 /// Shifts self left by `rhs` bits.
1016 /// Returns a tuple of the shifted version of self along with a boolean
1017 /// indicating whether the shift value was larger than or equal to the
1018 /// number of bits. If the shift value is too large, then value is
1019 /// masked (N-1) where N is the number of bits, and this value is then
1020 /// used to perform the shift.
1027 /// assert_eq!(0x10i32.overflowing_shl(4), (0x100, false));
1028 /// assert_eq!(0x10i32.overflowing_shl(36), (0x100, true));
1031 #[stable(feature = "wrapping", since = "1.7.0")]
1032 pub fn overflowing_shl(self, rhs
: u32) -> (Self, bool
) {
1033 (self.wrapping_shl(rhs
), (rhs
> ($BITS
- 1)))
1036 /// Shifts self right by `rhs` bits.
1038 /// Returns a tuple of the shifted version of self along with a boolean
1039 /// indicating whether the shift value was larger than or equal to the
1040 /// number of bits. If the shift value is too large, then value is
1041 /// masked (N-1) where N is the number of bits, and this value is then
1042 /// used to perform the shift.
1049 /// assert_eq!(0x10i32.overflowing_shr(4), (0x1, false));
1050 /// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
1053 #[stable(feature = "wrapping", since = "1.7.0")]
1054 pub fn overflowing_shr(self, rhs
: u32) -> (Self, bool
) {
1055 (self.wrapping_shr(rhs
), (rhs
> ($BITS
- 1)))
1058 /// Computes the absolute value of `self`.
1060 /// Returns a tuple of the absolute version of self along with a
1061 /// boolean indicating whether an overflow happened. If self is the
1062 /// minimum value (e.g. i32::MIN for values of type i32), then the
1063 /// minimum value will be returned again and true will be returned for
1064 /// an overflow happening.
1071 /// assert_eq!(10i8.overflowing_abs(), (10,false));
1072 /// assert_eq!((-10i8).overflowing_abs(), (10,false));
1073 /// assert_eq!((-128i8).overflowing_abs(), (-128,true));
1075 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1077 pub fn overflowing_abs(self) -> (Self, bool
) {
1078 if self.is_negative() {
1079 self.overflowing_neg()
1085 /// Raises self to the power of `exp`, using exponentiation by squaring.
1092 /// let x: i32 = 2; // or any other integer type
1094 /// assert_eq!(x.pow(4), 16);
1096 #[stable(feature = "rust1", since = "1.0.0")]
1098 #[rustc_inherit_overflow_checks]
1099 pub fn pow(self, mut exp
: u32) -> Self {
1100 let mut base
= self;
1111 // Deal with the final bit of the exponent separately, since
1112 // squaring the base afterwards is not necessary and may cause a
1113 // needless overflow.
1121 /// Computes the absolute value of `self`.
1123 /// # Overflow behavior
1125 /// The absolute value of `i32::min_value()` cannot be represented as an
1126 /// `i32`, and attempting to calculate it will cause an overflow. This
1127 /// means that code in debug mode will trigger a panic on this case and
1128 /// optimized code will return `i32::min_value()` without a panic.
1135 /// assert_eq!(10i8.abs(), 10);
1136 /// assert_eq!((-10i8).abs(), 10);
1138 #[stable(feature = "rust1", since = "1.0.0")]
1140 #[rustc_inherit_overflow_checks]
1141 pub fn abs(self) -> Self {
1142 if self.is_negative() {
1143 // Note that the #[inline] above means that the overflow
1144 // semantics of this negation depend on the crate we're being
1152 /// Returns a number representing sign of `self`.
1154 /// - `0` if the number is zero
1155 /// - `1` if the number is positive
1156 /// - `-1` if the number is negative
1163 /// assert_eq!(10i8.signum(), 1);
1164 /// assert_eq!(0i8.signum(), 0);
1165 /// assert_eq!((-10i8).signum(), -1);
1167 #[stable(feature = "rust1", since = "1.0.0")]
1169 pub fn signum(self) -> Self {
1177 /// Returns `true` if `self` is positive and `false` if the number
1178 /// is zero or negative.
1185 /// assert!(10i8.is_positive());
1186 /// assert!(!(-10i8).is_positive());
1188 #[stable(feature = "rust1", since = "1.0.0")]
1190 pub fn is_positive(self) -> bool { self > 0 }
1192 /// Returns `true` if `self` is negative and `false` if the number
1193 /// is zero or positive.
1200 /// assert!((-10i8).is_negative());
1201 /// assert!(!10i8.is_negative());
1203 #[stable(feature = "rust1", since = "1.0.0")]
1205 pub fn is_negative(self) -> bool { self < 0 }
1211 int_impl
! { i8, i8, u8, 8 }
1216 int_impl
! { i16, i16, u16, 16 }
1221 int_impl
! { i32, i32, u32, 32 }
1226 int_impl
! { i64, i64, u64, 64 }
1231 int_impl
! { i128, i128, u128, 128 }
1234 #[cfg(target_pointer_width = "16")]
1237 int_impl
! { isize, i16, u16, 16 }
1240 #[cfg(target_pointer_width = "32")]
1243 int_impl
! { isize, i32, u32, 32 }
1246 #[cfg(target_pointer_width = "64")]
1249 int_impl
! { isize, i64, u64, 64 }
1252 // `Int` + `UnsignedInt` implemented for unsigned integers
1253 macro_rules
! uint_impl
{
1254 ($SelfT
:ty
, $ActualT
:ty
, $BITS
:expr
) => {
1255 /// Returns the smallest value that can be represented by this integer type.
1262 /// assert_eq!(u8::min_value(), 0);
1264 #[stable(feature = "rust1", since = "1.0.0")]
1266 pub const fn min_value() -> Self { 0 }
1268 /// Returns the largest value that can be represented by this integer type.
1275 /// assert_eq!(u8::max_value(), 255);
1277 #[stable(feature = "rust1", since = "1.0.0")]
1279 pub const fn max_value() -> Self { !0 }
1281 /// Converts a string slice in a given base to an integer.
1283 /// The string is expected to be an optional `+` sign
1284 /// followed by digits.
1285 /// Leading and trailing whitespace represent an error.
1286 /// Digits are a subset of these characters, depending on `radix`:
1294 /// This function panics if `radix` is not in the range from 2 to 36.
1301 /// assert_eq!(u32::from_str_radix("A", 16), Ok(10));
1303 #[stable(feature = "rust1", since = "1.0.0")]
1304 pub fn from_str_radix(src
: &str, radix
: u32) -> Result
<Self, ParseIntError
> {
1305 from_str_radix(src
, radix
)
1308 /// Returns the number of ones in the binary representation of `self`.
1315 /// let n = 0b01001100u8;
1317 /// assert_eq!(n.count_ones(), 3);
1319 #[stable(feature = "rust1", since = "1.0.0")]
1321 pub fn count_ones(self) -> u32 {
1322 unsafe { intrinsics::ctpop(self as $ActualT) as u32 }
1325 /// Returns the number of zeros in the binary representation of `self`.
1332 /// let n = 0b01001100u8;
1334 /// assert_eq!(n.count_zeros(), 5);
1336 #[stable(feature = "rust1", since = "1.0.0")]
1338 pub fn count_zeros(self) -> u32 {
1339 (!self).count_ones()
1342 /// Returns the number of leading zeros in the binary representation
1350 /// let n = 0b0101000u16;
1352 /// assert_eq!(n.leading_zeros(), 10);
1354 #[stable(feature = "rust1", since = "1.0.0")]
1356 pub fn leading_zeros(self) -> u32 {
1357 unsafe { intrinsics::ctlz(self as $ActualT) as u32 }
1360 /// Returns the number of trailing zeros in the binary representation
1368 /// let n = 0b0101000u16;
1370 /// assert_eq!(n.trailing_zeros(), 3);
1372 #[stable(feature = "rust1", since = "1.0.0")]
1374 pub fn trailing_zeros(self) -> u32 {
1375 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
1376 // emits two conditional moves on x86_64. By promoting the value to
1377 // u16 and setting bit 8, we get better code without any conditional
1379 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
1380 // pending, remove this workaround once LLVM generates better code
1384 intrinsics
::cttz(self as u16 | 0x100) as u32
1386 intrinsics
::cttz(self) as u32
1391 /// Shifts the bits to the left by a specified amount, `n`,
1392 /// wrapping the truncated bits to the end of the resulting integer.
1394 /// Please note this isn't the same operation as `<<`!
1401 /// let n = 0x0123456789ABCDEFu64;
1402 /// let m = 0x3456789ABCDEF012u64;
1404 /// assert_eq!(n.rotate_left(12), m);
1406 #[stable(feature = "rust1", since = "1.0.0")]
1408 pub fn rotate_left(self, n
: u32) -> Self {
1409 // Protect against undefined behaviour for over-long bit shifts
1411 (self << n
) | (self >> (($BITS
- n
) % $BITS
))
1414 /// Shifts the bits to the right by a specified amount, `n`,
1415 /// wrapping the truncated bits to the beginning of the resulting
1418 /// Please note this isn't the same operation as `>>`!
1425 /// let n = 0x0123456789ABCDEFu64;
1426 /// let m = 0xDEF0123456789ABCu64;
1428 /// assert_eq!(n.rotate_right(12), m);
1430 #[stable(feature = "rust1", since = "1.0.0")]
1432 pub fn rotate_right(self, n
: u32) -> Self {
1433 // Protect against undefined behaviour for over-long bit shifts
1435 (self >> n
) | (self << (($BITS
- n
) % $BITS
))
1438 /// Reverses the byte order of the integer.
1445 /// let n: u16 = 0b0000000_01010101;
1446 /// assert_eq!(n, 85);
1448 /// let m = n.swap_bytes();
1450 /// assert_eq!(m, 0b01010101_00000000);
1451 /// assert_eq!(m, 21760);
1453 #[stable(feature = "rust1", since = "1.0.0")]
1455 pub fn swap_bytes(self) -> Self {
1456 unsafe { intrinsics::bswap(self as $ActualT) as Self }
1459 /// Converts an integer from big endian to the target's endianness.
1461 /// On big endian this is a no-op. On little endian the bytes are
1469 /// let n = 0x0123456789ABCDEFu64;
1471 /// if cfg!(target_endian = "big") {
1472 /// assert_eq!(u64::from_be(n), n)
1474 /// assert_eq!(u64::from_be(n), n.swap_bytes())
1477 #[stable(feature = "rust1", since = "1.0.0")]
1479 pub fn from_be(x
: Self) -> Self {
1480 if cfg
!(target_endian
= "big") { x }
else { x.swap_bytes() }
1483 /// Converts an integer from little endian to the target's endianness.
1485 /// On little endian this is a no-op. On big endian the bytes are
1493 /// let n = 0x0123456789ABCDEFu64;
1495 /// if cfg!(target_endian = "little") {
1496 /// assert_eq!(u64::from_le(n), n)
1498 /// assert_eq!(u64::from_le(n), n.swap_bytes())
1501 #[stable(feature = "rust1", since = "1.0.0")]
1503 pub fn from_le(x
: Self) -> Self {
1504 if cfg
!(target_endian
= "little") { x }
else { x.swap_bytes() }
1507 /// Converts `self` to big endian from the target's endianness.
1509 /// On big endian this is a no-op. On little endian the bytes are
1517 /// let n = 0x0123456789ABCDEFu64;
1519 /// if cfg!(target_endian = "big") {
1520 /// assert_eq!(n.to_be(), n)
1522 /// assert_eq!(n.to_be(), n.swap_bytes())
1525 #[stable(feature = "rust1", since = "1.0.0")]
1527 pub fn to_be(self) -> Self { // or not to be?
1528 if cfg
!(target_endian
= "big") { self }
else { self.swap_bytes() }
1531 /// Converts `self` to little endian from the target's endianness.
1533 /// On little endian this is a no-op. On big endian the bytes are
1541 /// let n = 0x0123456789ABCDEFu64;
1543 /// if cfg!(target_endian = "little") {
1544 /// assert_eq!(n.to_le(), n)
1546 /// assert_eq!(n.to_le(), n.swap_bytes())
1549 #[stable(feature = "rust1", since = "1.0.0")]
1551 pub fn to_le(self) -> Self {
1552 if cfg
!(target_endian
= "little") { self }
else { self.swap_bytes() }
1555 /// Checked integer addition. Computes `self + rhs`, returning `None`
1556 /// if overflow occurred.
1563 /// assert_eq!(5u16.checked_add(65530), Some(65535));
1564 /// assert_eq!(6u16.checked_add(65530), None);
1566 #[stable(feature = "rust1", since = "1.0.0")]
1568 pub fn checked_add(self, rhs
: Self) -> Option
<Self> {
1569 let (a
, b
) = self.overflowing_add(rhs
);
1570 if b {None}
else {Some(a)}
1573 /// Checked integer subtraction. Computes `self - rhs`, returning
1574 /// `None` if overflow occurred.
1581 /// assert_eq!(1u8.checked_sub(1), Some(0));
1582 /// assert_eq!(0u8.checked_sub(1), None);
1584 #[stable(feature = "rust1", since = "1.0.0")]
1586 pub fn checked_sub(self, rhs
: Self) -> Option
<Self> {
1587 let (a
, b
) = self.overflowing_sub(rhs
);
1588 if b {None}
else {Some(a)}
1591 /// Checked integer multiplication. Computes `self * rhs`, returning
1592 /// `None` if overflow occurred.
1599 /// assert_eq!(5u8.checked_mul(51), Some(255));
1600 /// assert_eq!(5u8.checked_mul(52), None);
1602 #[stable(feature = "rust1", since = "1.0.0")]
1604 pub fn checked_mul(self, rhs
: Self) -> Option
<Self> {
1605 let (a
, b
) = self.overflowing_mul(rhs
);
1606 if b {None}
else {Some(a)}
1609 /// Checked integer division. Computes `self / rhs`, returning `None`
1617 /// assert_eq!(128u8.checked_div(2), Some(64));
1618 /// assert_eq!(1u8.checked_div(0), None);
1620 #[stable(feature = "rust1", since = "1.0.0")]
1622 pub fn checked_div(self, rhs
: Self) -> Option
<Self> {
1625 rhs
=> Some(unsafe { intrinsics::unchecked_div(self, rhs) }
),
1629 /// Checked integer remainder. Computes `self % rhs`, returning `None`
1637 /// assert_eq!(5u32.checked_rem(2), Some(1));
1638 /// assert_eq!(5u32.checked_rem(0), None);
1640 #[stable(feature = "wrapping", since = "1.7.0")]
1642 pub fn checked_rem(self, rhs
: Self) -> Option
<Self> {
1646 Some(unsafe { intrinsics::unchecked_rem(self, rhs) }
)
1650 /// Checked negation. Computes `-self`, returning `None` unless `self ==
1653 /// Note that negating any positive integer will overflow.
1660 /// assert_eq!(0u32.checked_neg(), Some(0));
1661 /// assert_eq!(1u32.checked_neg(), None);
1663 #[stable(feature = "wrapping", since = "1.7.0")]
1665 pub fn checked_neg(self) -> Option
<Self> {
1666 let (a
, b
) = self.overflowing_neg();
1667 if b {None}
else {Some(a)}
1670 /// Checked shift left. Computes `self << rhs`, returning `None`
1671 /// if `rhs` is larger than or equal to the number of bits in `self`.
1678 /// assert_eq!(0x10u32.checked_shl(4), Some(0x100));
1679 /// assert_eq!(0x10u32.checked_shl(33), None);
1681 #[stable(feature = "wrapping", since = "1.7.0")]
1683 pub fn checked_shl(self, rhs
: u32) -> Option
<Self> {
1684 let (a
, b
) = self.overflowing_shl(rhs
);
1685 if b {None}
else {Some(a)}
1688 /// Checked shift right. Computes `self >> rhs`, returning `None`
1689 /// if `rhs` is larger than or equal to the number of bits in `self`.
1696 /// assert_eq!(0x10u32.checked_shr(4), Some(0x1));
1697 /// assert_eq!(0x10u32.checked_shr(33), None);
1699 #[stable(feature = "wrapping", since = "1.7.0")]
1701 pub fn checked_shr(self, rhs
: u32) -> Option
<Self> {
1702 let (a
, b
) = self.overflowing_shr(rhs
);
1703 if b {None}
else {Some(a)}
1706 /// Saturating integer addition. Computes `self + rhs`, saturating at
1707 /// the numeric bounds instead of overflowing.
1714 /// assert_eq!(100u8.saturating_add(1), 101);
1715 /// assert_eq!(200u8.saturating_add(127), 255);
1717 #[stable(feature = "rust1", since = "1.0.0")]
1719 pub fn saturating_add(self, rhs
: Self) -> Self {
1720 match self.checked_add(rhs
) {
1722 None
=> Self::max_value(),
1726 /// Saturating integer subtraction. Computes `self - rhs`, saturating
1727 /// at the numeric bounds instead of overflowing.
1734 /// assert_eq!(100u8.saturating_sub(27), 73);
1735 /// assert_eq!(13u8.saturating_sub(127), 0);
1737 #[stable(feature = "rust1", since = "1.0.0")]
1739 pub fn saturating_sub(self, rhs
: Self) -> Self {
1740 match self.checked_sub(rhs
) {
1742 None
=> Self::min_value(),
1746 /// Saturating integer multiplication. Computes `self * rhs`,
1747 /// saturating at the numeric bounds instead of overflowing.
1756 /// assert_eq!(100u32.saturating_mul(127), 12700);
1757 /// assert_eq!((1u32 << 23).saturating_mul(1 << 23), u32::MAX);
1759 #[stable(feature = "wrapping", since = "1.7.0")]
1761 pub fn saturating_mul(self, rhs
: Self) -> Self {
1762 self.checked_mul(rhs
).unwrap_or(Self::max_value())
1765 /// Wrapping (modular) addition. Computes `self + rhs`,
1766 /// wrapping around at the boundary of the type.
1773 /// assert_eq!(200u8.wrapping_add(55), 255);
1774 /// assert_eq!(200u8.wrapping_add(155), 99);
1776 #[stable(feature = "rust1", since = "1.0.0")]
1778 pub fn wrapping_add(self, rhs
: Self) -> Self {
1780 intrinsics
::overflowing_add(self, rhs
)
1784 /// Wrapping (modular) subtraction. Computes `self - rhs`,
1785 /// wrapping around at the boundary of the type.
1792 /// assert_eq!(100u8.wrapping_sub(100), 0);
1793 /// assert_eq!(100u8.wrapping_sub(155), 201);
1795 #[stable(feature = "rust1", since = "1.0.0")]
1797 pub fn wrapping_sub(self, rhs
: Self) -> Self {
1799 intrinsics
::overflowing_sub(self, rhs
)
1803 /// Wrapping (modular) multiplication. Computes `self *
1804 /// rhs`, wrapping around at the boundary of the type.
1811 /// assert_eq!(10u8.wrapping_mul(12), 120);
1812 /// assert_eq!(25u8.wrapping_mul(12), 44);
1814 #[stable(feature = "rust1", since = "1.0.0")]
1816 pub fn wrapping_mul(self, rhs
: Self) -> Self {
1818 intrinsics
::overflowing_mul(self, rhs
)
1822 /// Wrapping (modular) division. Computes `self / rhs`.
1823 /// Wrapped division on unsigned types is just normal division.
1824 /// There's no way wrapping could ever happen.
1825 /// This function exists, so that all operations
1826 /// are accounted for in the wrapping operations.
1833 /// assert_eq!(100u8.wrapping_div(10), 10);
1835 #[stable(feature = "num_wrapping", since = "1.2.0")]
1837 pub fn wrapping_div(self, rhs
: Self) -> Self {
1841 /// Wrapping (modular) remainder. Computes `self % rhs`.
1842 /// Wrapped remainder calculation on unsigned types is
1843 /// just the regular remainder calculation.
1844 /// There's no way wrapping could ever happen.
1845 /// This function exists, so that all operations
1846 /// are accounted for in the wrapping operations.
1853 /// assert_eq!(100u8.wrapping_rem(10), 0);
1855 #[stable(feature = "num_wrapping", since = "1.2.0")]
1857 pub fn wrapping_rem(self, rhs
: Self) -> Self {
1861 /// Wrapping (modular) negation. Computes `-self`,
1862 /// wrapping around at the boundary of the type.
1864 /// Since unsigned types do not have negative equivalents
1865 /// all applications of this function will wrap (except for `-0`).
1866 /// For values smaller than the corresponding signed type's maximum
1867 /// the result is the same as casting the corresponding signed value.
1868 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
1869 /// `MAX` is the corresponding signed type's maximum.
1876 /// assert_eq!(100u8.wrapping_neg(), 156);
1877 /// assert_eq!(0u8.wrapping_neg(), 0);
1878 /// assert_eq!(180u8.wrapping_neg(), 76);
1879 /// assert_eq!(180u8.wrapping_neg(), (127 + 1) - (180u8 - (127 + 1)));
1881 #[stable(feature = "num_wrapping", since = "1.2.0")]
1883 pub fn wrapping_neg(self) -> Self {
1884 self.overflowing_neg().0
1887 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1888 /// where `mask` removes any high-order bits of `rhs` that
1889 /// would cause the shift to exceed the bitwidth of the type.
1891 /// Note that this is *not* the same as a rotate-left; the
1892 /// RHS of a wrapping shift-left is restricted to the range
1893 /// of the type, rather than the bits shifted out of the LHS
1894 /// being returned to the other end. The primitive integer
1895 /// types all implement a `rotate_left` function, which may
1896 /// be what you want instead.
1903 /// assert_eq!(1u8.wrapping_shl(7), 128);
1904 /// assert_eq!(1u8.wrapping_shl(8), 1);
1906 #[stable(feature = "num_wrapping", since = "1.2.0")]
1908 pub fn wrapping_shl(self, rhs
: u32) -> Self {
1910 intrinsics
::unchecked_shl(self, (rhs
& ($BITS
- 1)) as $SelfT
)
1914 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
1915 /// where `mask` removes any high-order bits of `rhs` that
1916 /// would cause the shift to exceed the bitwidth of the type.
1918 /// Note that this is *not* the same as a rotate-right; the
1919 /// RHS of a wrapping shift-right is restricted to the range
1920 /// of the type, rather than the bits shifted out of the LHS
1921 /// being returned to the other end. The primitive integer
1922 /// types all implement a `rotate_right` function, which may
1923 /// be what you want instead.
1930 /// assert_eq!(128u8.wrapping_shr(7), 1);
1931 /// assert_eq!(128u8.wrapping_shr(8), 128);
1933 #[stable(feature = "num_wrapping", since = "1.2.0")]
1935 pub fn wrapping_shr(self, rhs
: u32) -> Self {
1937 intrinsics
::unchecked_shr(self, (rhs
& ($BITS
- 1)) as $SelfT
)
1941 /// Calculates `self` + `rhs`
1943 /// Returns a tuple of the addition along with a boolean indicating
1944 /// whether an arithmetic overflow would occur. If an overflow would
1945 /// have occurred then the wrapped value is returned.
1954 /// assert_eq!(5u32.overflowing_add(2), (7, false));
1955 /// assert_eq!(u32::MAX.overflowing_add(1), (0, true));
1958 #[stable(feature = "wrapping", since = "1.7.0")]
1959 pub fn overflowing_add(self, rhs
: Self) -> (Self, bool
) {
1960 let (a
, b
) = unsafe {
1961 intrinsics
::add_with_overflow(self as $ActualT
,
1967 /// Calculates `self` - `rhs`
1969 /// Returns a tuple of the subtraction along with a boolean indicating
1970 /// whether an arithmetic overflow would occur. If an overflow would
1971 /// have occurred then the wrapped value is returned.
1980 /// assert_eq!(5u32.overflowing_sub(2), (3, false));
1981 /// assert_eq!(0u32.overflowing_sub(1), (u32::MAX, true));
1984 #[stable(feature = "wrapping", since = "1.7.0")]
1985 pub fn overflowing_sub(self, rhs
: Self) -> (Self, bool
) {
1986 let (a
, b
) = unsafe {
1987 intrinsics
::sub_with_overflow(self as $ActualT
,
1993 /// Calculates the multiplication of `self` and `rhs`.
1995 /// Returns a tuple of the multiplication along with a boolean
1996 /// indicating whether an arithmetic overflow would occur. If an
1997 /// overflow would have occurred then the wrapped value is returned.
2004 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
2005 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
2008 #[stable(feature = "wrapping", since = "1.7.0")]
2009 pub fn overflowing_mul(self, rhs
: Self) -> (Self, bool
) {
2010 let (a
, b
) = unsafe {
2011 intrinsics
::mul_with_overflow(self as $ActualT
,
2017 /// Calculates the divisor when `self` is divided by `rhs`.
2019 /// Returns a tuple of the divisor along with a boolean indicating
2020 /// whether an arithmetic overflow would occur. Note that for unsigned
2021 /// integers overflow never occurs, so the second value is always
2026 /// This function will panic if `rhs` is 0.
2033 /// assert_eq!(5u32.overflowing_div(2), (2, false));
2036 #[stable(feature = "wrapping", since = "1.7.0")]
2037 pub fn overflowing_div(self, rhs
: Self) -> (Self, bool
) {
2041 /// Calculates the remainder when `self` is divided by `rhs`.
2043 /// Returns a tuple of the remainder after dividing along with a boolean
2044 /// indicating whether an arithmetic overflow would occur. Note that for
2045 /// unsigned integers overflow never occurs, so the second value is
2050 /// This function will panic if `rhs` is 0.
2057 /// assert_eq!(5u32.overflowing_rem(2), (1, false));
2060 #[stable(feature = "wrapping", since = "1.7.0")]
2061 pub fn overflowing_rem(self, rhs
: Self) -> (Self, bool
) {
2065 /// Negates self in an overflowing fashion.
2067 /// Returns `!self + 1` using wrapping operations to return the value
2068 /// that represents the negation of this unsigned value. Note that for
2069 /// positive unsigned values overflow always occurs, but negating 0 does
2077 /// assert_eq!(0u32.overflowing_neg(), (0, false));
2078 /// assert_eq!(2u32.overflowing_neg(), (-2i32 as u32, true));
2081 #[stable(feature = "wrapping", since = "1.7.0")]
2082 pub fn overflowing_neg(self) -> (Self, bool
) {
2083 ((!self).wrapping_add(1), self != 0)
2086 /// Shifts self left by `rhs` bits.
2088 /// Returns a tuple of the shifted version of self along with a boolean
2089 /// indicating whether the shift value was larger than or equal to the
2090 /// number of bits. If the shift value is too large, then value is
2091 /// masked (N-1) where N is the number of bits, and this value is then
2092 /// used to perform the shift.
2099 /// assert_eq!(0x10u32.overflowing_shl(4), (0x100, false));
2100 /// assert_eq!(0x10u32.overflowing_shl(36), (0x100, true));
2103 #[stable(feature = "wrapping", since = "1.7.0")]
2104 pub fn overflowing_shl(self, rhs
: u32) -> (Self, bool
) {
2105 (self.wrapping_shl(rhs
), (rhs
> ($BITS
- 1)))
2108 /// Shifts self right by `rhs` bits.
2110 /// Returns a tuple of the shifted version of self along with a boolean
2111 /// indicating whether the shift value was larger than or equal to the
2112 /// number of bits. If the shift value is too large, then value is
2113 /// masked (N-1) where N is the number of bits, and this value is then
2114 /// used to perform the shift.
2121 /// assert_eq!(0x10u32.overflowing_shr(4), (0x1, false));
2122 /// assert_eq!(0x10u32.overflowing_shr(36), (0x1, true));
2125 #[stable(feature = "wrapping", since = "1.7.0")]
2126 pub fn overflowing_shr(self, rhs
: u32) -> (Self, bool
) {
2127 (self.wrapping_shr(rhs
), (rhs
> ($BITS
- 1)))
2131 /// Raises self to the power of `exp`, using exponentiation by squaring.
2138 /// assert_eq!(2u32.pow(4), 16);
2140 #[stable(feature = "rust1", since = "1.0.0")]
2142 #[rustc_inherit_overflow_checks]
2143 pub fn pow(self, mut exp
: u32) -> Self {
2144 let mut base
= self;
2155 // Deal with the final bit of the exponent separately, since
2156 // squaring the base afterwards is not necessary and may cause a
2157 // needless overflow.
2165 /// Returns `true` if and only if `self == 2^k` for some `k`.
2172 /// assert!(16u8.is_power_of_two());
2173 /// assert!(!10u8.is_power_of_two());
2175 #[stable(feature = "rust1", since = "1.0.0")]
2177 pub fn is_power_of_two(self) -> bool
{
2178 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
2181 // Returns one less than next power of two.
2182 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
2184 // 8u8.one_less_than_next_power_of_two() == 7
2185 // 6u8.one_less_than_next_power_of_two() == 7
2187 // This method cannot overflow, as in the `next_power_of_two`
2188 // overflow cases it instead ends up returning the maximum value
2189 // of the type, and can return 0 for 0.
2191 fn one_less_than_next_power_of_two(self) -> Self {
2192 if self <= 1 { return 0; }
2194 // Because `p > 0`, it cannot consist entirely of leading zeros.
2195 // That means the shift is always in-bounds, and some processors
2196 // (such as intel pre-haswell) have more efficient ctlz
2197 // intrinsics when the argument is non-zero.
2199 let z
= unsafe { intrinsics::ctlz_nonzero(p) }
;
2200 <$SelfT
>::max_value() >> z
2203 /// Returns the smallest power of two greater than or equal to `self`.
2205 /// When return value overflows (i.e. `self > (1 << (N-1))` for type
2206 /// `uN`), it panics in debug mode and return value is wrapped to 0 in
2207 /// release mode (the only situation in which method can return 0).
2214 /// assert_eq!(2u8.next_power_of_two(), 2);
2215 /// assert_eq!(3u8.next_power_of_two(), 4);
2217 #[stable(feature = "rust1", since = "1.0.0")]
2219 pub fn next_power_of_two(self) -> Self {
2220 // Call the trait to get overflow checks
2221 ops
::Add
::add(self.one_less_than_next_power_of_two(), 1)
2224 /// Returns the smallest power of two greater than or equal to `n`. If
2225 /// the next power of two is greater than the type's maximum value,
2226 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
2233 /// assert_eq!(2u8.checked_next_power_of_two(), Some(2));
2234 /// assert_eq!(3u8.checked_next_power_of_two(), Some(4));
2235 /// assert_eq!(200u8.checked_next_power_of_two(), None);
2237 #[stable(feature = "rust1", since = "1.0.0")]
2238 pub fn checked_next_power_of_two(self) -> Option
<Self> {
2239 self.one_less_than_next_power_of_two().checked_add(1)
2246 uint_impl
! { u8, u8, 8 }
2249 /// Checks if the value is within the ASCII range.
2254 /// let ascii = 97u8;
2255 /// let non_ascii = 150u8;
2257 /// assert!(ascii.is_ascii());
2258 /// assert!(!non_ascii.is_ascii());
2260 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2262 pub fn is_ascii(&self) -> bool
{
2266 /// Makes a copy of the value in its ASCII upper case equivalent.
2268 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2269 /// but non-ASCII letters are unchanged.
2271 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
2276 /// let lowercase_a = 97u8;
2278 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
2281 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
2282 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2284 pub fn to_ascii_uppercase(&self) -> u8 {
2285 ASCII_UPPERCASE_MAP
[*self as usize]
2288 /// Makes a copy of the value in its ASCII lower case equivalent.
2290 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2291 /// but non-ASCII letters are unchanged.
2293 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
2298 /// let uppercase_a = 65u8;
2300 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
2303 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
2304 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2306 pub fn to_ascii_lowercase(&self) -> u8 {
2307 ASCII_LOWERCASE_MAP
[*self as usize]
2310 /// Checks that two values are an ASCII case-insensitive match.
2312 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
2317 /// let lowercase_a = 97u8;
2318 /// let uppercase_a = 65u8;
2320 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
2322 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2324 pub fn eq_ignore_ascii_case(&self, other
: &u8) -> bool
{
2325 self.to_ascii_lowercase() == other
.to_ascii_lowercase()
2328 /// Converts this value to its ASCII upper case equivalent in-place.
2330 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2331 /// but non-ASCII letters are unchanged.
2333 /// To return a new uppercased value without modifying the existing one, use
2334 /// [`to_ascii_uppercase`].
2339 /// let mut byte = b'a';
2341 /// byte.make_ascii_uppercase();
2343 /// assert_eq!(b'A', byte);
2346 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
2347 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2349 pub fn make_ascii_uppercase(&mut self) {
2350 *self = self.to_ascii_uppercase();
2353 /// Converts this value to its ASCII lower case equivalent in-place.
2355 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2356 /// but non-ASCII letters are unchanged.
2358 /// To return a new lowercased value without modifying the existing one, use
2359 /// [`to_ascii_lowercase`].
2364 /// let mut byte = b'A';
2366 /// byte.make_ascii_lowercase();
2368 /// assert_eq!(b'a', byte);
2371 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
2372 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2374 pub fn make_ascii_lowercase(&mut self) {
2375 *self = self.to_ascii_lowercase();
2378 /// Checks if the value is an ASCII alphabetic character:
2380 /// - U+0041 'A' ... U+005A 'Z', or
2381 /// - U+0061 'a' ... U+007A 'z'.
2386 /// #![feature(ascii_ctype)]
2388 /// let uppercase_a = b'A';
2389 /// let uppercase_g = b'G';
2392 /// let zero = b'0';
2393 /// let percent = b'%';
2394 /// let space = b' ';
2396 /// let esc = 0x1b_u8;
2398 /// assert!(uppercase_a.is_ascii_alphabetic());
2399 /// assert!(uppercase_g.is_ascii_alphabetic());
2400 /// assert!(a.is_ascii_alphabetic());
2401 /// assert!(g.is_ascii_alphabetic());
2402 /// assert!(!zero.is_ascii_alphabetic());
2403 /// assert!(!percent.is_ascii_alphabetic());
2404 /// assert!(!space.is_ascii_alphabetic());
2405 /// assert!(!lf.is_ascii_alphabetic());
2406 /// assert!(!esc.is_ascii_alphabetic());
2408 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2410 pub fn is_ascii_alphabetic(&self) -> bool
{
2411 if *self >= 0x80 { return false; }
2412 match ASCII_CHARACTER_CLASS
[*self as usize] {
2413 L
| Lx
| U
| Ux
=> true,
2418 /// Checks if the value is an ASCII uppercase character:
2419 /// U+0041 'A' ... U+005A 'Z'.
2424 /// #![feature(ascii_ctype)]
2426 /// let uppercase_a = b'A';
2427 /// let uppercase_g = b'G';
2430 /// let zero = b'0';
2431 /// let percent = b'%';
2432 /// let space = b' ';
2434 /// let esc = 0x1b_u8;
2436 /// assert!(uppercase_a.is_ascii_uppercase());
2437 /// assert!(uppercase_g.is_ascii_uppercase());
2438 /// assert!(!a.is_ascii_uppercase());
2439 /// assert!(!g.is_ascii_uppercase());
2440 /// assert!(!zero.is_ascii_uppercase());
2441 /// assert!(!percent.is_ascii_uppercase());
2442 /// assert!(!space.is_ascii_uppercase());
2443 /// assert!(!lf.is_ascii_uppercase());
2444 /// assert!(!esc.is_ascii_uppercase());
2446 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2448 pub fn is_ascii_uppercase(&self) -> bool
{
2449 if *self >= 0x80 { return false }
2450 match ASCII_CHARACTER_CLASS
[*self as usize] {
2456 /// Checks if the value is an ASCII lowercase character:
2457 /// U+0061 'a' ... U+007A 'z'.
2462 /// #![feature(ascii_ctype)]
2464 /// let uppercase_a = b'A';
2465 /// let uppercase_g = b'G';
2468 /// let zero = b'0';
2469 /// let percent = b'%';
2470 /// let space = b' ';
2472 /// let esc = 0x1b_u8;
2474 /// assert!(!uppercase_a.is_ascii_lowercase());
2475 /// assert!(!uppercase_g.is_ascii_lowercase());
2476 /// assert!(a.is_ascii_lowercase());
2477 /// assert!(g.is_ascii_lowercase());
2478 /// assert!(!zero.is_ascii_lowercase());
2479 /// assert!(!percent.is_ascii_lowercase());
2480 /// assert!(!space.is_ascii_lowercase());
2481 /// assert!(!lf.is_ascii_lowercase());
2482 /// assert!(!esc.is_ascii_lowercase());
2484 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2486 pub fn is_ascii_lowercase(&self) -> bool
{
2487 if *self >= 0x80 { return false }
2488 match ASCII_CHARACTER_CLASS
[*self as usize] {
2494 /// Checks if the value is an ASCII alphanumeric character:
2496 /// - U+0041 'A' ... U+005A 'Z', or
2497 /// - U+0061 'a' ... U+007A 'z', or
2498 /// - U+0030 '0' ... U+0039 '9'.
2503 /// #![feature(ascii_ctype)]
2505 /// let uppercase_a = b'A';
2506 /// let uppercase_g = b'G';
2509 /// let zero = b'0';
2510 /// let percent = b'%';
2511 /// let space = b' ';
2513 /// let esc = 0x1b_u8;
2515 /// assert!(uppercase_a.is_ascii_alphanumeric());
2516 /// assert!(uppercase_g.is_ascii_alphanumeric());
2517 /// assert!(a.is_ascii_alphanumeric());
2518 /// assert!(g.is_ascii_alphanumeric());
2519 /// assert!(zero.is_ascii_alphanumeric());
2520 /// assert!(!percent.is_ascii_alphanumeric());
2521 /// assert!(!space.is_ascii_alphanumeric());
2522 /// assert!(!lf.is_ascii_alphanumeric());
2523 /// assert!(!esc.is_ascii_alphanumeric());
2525 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2527 pub fn is_ascii_alphanumeric(&self) -> bool
{
2528 if *self >= 0x80 { return false }
2529 match ASCII_CHARACTER_CLASS
[*self as usize] {
2530 D
| L
| Lx
| U
| Ux
=> true,
2535 /// Checks if the value is an ASCII decimal digit:
2536 /// U+0030 '0' ... U+0039 '9'.
2541 /// #![feature(ascii_ctype)]
2543 /// let uppercase_a = b'A';
2544 /// let uppercase_g = b'G';
2547 /// let zero = b'0';
2548 /// let percent = b'%';
2549 /// let space = b' ';
2551 /// let esc = 0x1b_u8;
2553 /// assert!(!uppercase_a.is_ascii_digit());
2554 /// assert!(!uppercase_g.is_ascii_digit());
2555 /// assert!(!a.is_ascii_digit());
2556 /// assert!(!g.is_ascii_digit());
2557 /// assert!(zero.is_ascii_digit());
2558 /// assert!(!percent.is_ascii_digit());
2559 /// assert!(!space.is_ascii_digit());
2560 /// assert!(!lf.is_ascii_digit());
2561 /// assert!(!esc.is_ascii_digit());
2563 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2565 pub fn is_ascii_digit(&self) -> bool
{
2566 if *self >= 0x80 { return false }
2567 match ASCII_CHARACTER_CLASS
[*self as usize] {
2573 /// Checks if the value is an ASCII hexadecimal digit:
2575 /// - U+0030 '0' ... U+0039 '9', or
2576 /// - U+0041 'A' ... U+0046 'F', or
2577 /// - U+0061 'a' ... U+0066 'f'.
2582 /// #![feature(ascii_ctype)]
2584 /// let uppercase_a = b'A';
2585 /// let uppercase_g = b'G';
2588 /// let zero = b'0';
2589 /// let percent = b'%';
2590 /// let space = b' ';
2592 /// let esc = 0x1b_u8;
2594 /// assert!(uppercase_a.is_ascii_hexdigit());
2595 /// assert!(!uppercase_g.is_ascii_hexdigit());
2596 /// assert!(a.is_ascii_hexdigit());
2597 /// assert!(!g.is_ascii_hexdigit());
2598 /// assert!(zero.is_ascii_hexdigit());
2599 /// assert!(!percent.is_ascii_hexdigit());
2600 /// assert!(!space.is_ascii_hexdigit());
2601 /// assert!(!lf.is_ascii_hexdigit());
2602 /// assert!(!esc.is_ascii_hexdigit());
2604 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2606 pub fn is_ascii_hexdigit(&self) -> bool
{
2607 if *self >= 0x80 { return false }
2608 match ASCII_CHARACTER_CLASS
[*self as usize] {
2609 D
| Lx
| Ux
=> true,
2614 /// Checks if the value is an ASCII punctuation character:
2616 /// - U+0021 ... U+002F `! " # $ % & ' ( ) * + , - . /`, or
2617 /// - U+003A ... U+0040 `: ; < = > ? @`, or
2618 /// - U+005B ... U+0060 ``[ \ ] ^ _ ` ``, or
2619 /// - U+007B ... U+007E `{ | } ~`
2624 /// #![feature(ascii_ctype)]
2626 /// let uppercase_a = b'A';
2627 /// let uppercase_g = b'G';
2630 /// let zero = b'0';
2631 /// let percent = b'%';
2632 /// let space = b' ';
2634 /// let esc = 0x1b_u8;
2636 /// assert!(!uppercase_a.is_ascii_punctuation());
2637 /// assert!(!uppercase_g.is_ascii_punctuation());
2638 /// assert!(!a.is_ascii_punctuation());
2639 /// assert!(!g.is_ascii_punctuation());
2640 /// assert!(!zero.is_ascii_punctuation());
2641 /// assert!(percent.is_ascii_punctuation());
2642 /// assert!(!space.is_ascii_punctuation());
2643 /// assert!(!lf.is_ascii_punctuation());
2644 /// assert!(!esc.is_ascii_punctuation());
2646 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2648 pub fn is_ascii_punctuation(&self) -> bool
{
2649 if *self >= 0x80 { return false }
2650 match ASCII_CHARACTER_CLASS
[*self as usize] {
2656 /// Checks if the value is an ASCII graphic character:
2657 /// U+0021 '@' ... U+007E '~'.
2662 /// #![feature(ascii_ctype)]
2664 /// let uppercase_a = b'A';
2665 /// let uppercase_g = b'G';
2668 /// let zero = b'0';
2669 /// let percent = b'%';
2670 /// let space = b' ';
2672 /// let esc = 0x1b_u8;
2674 /// assert!(uppercase_a.is_ascii_graphic());
2675 /// assert!(uppercase_g.is_ascii_graphic());
2676 /// assert!(a.is_ascii_graphic());
2677 /// assert!(g.is_ascii_graphic());
2678 /// assert!(zero.is_ascii_graphic());
2679 /// assert!(percent.is_ascii_graphic());
2680 /// assert!(!space.is_ascii_graphic());
2681 /// assert!(!lf.is_ascii_graphic());
2682 /// assert!(!esc.is_ascii_graphic());
2684 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2686 pub fn is_ascii_graphic(&self) -> bool
{
2687 if *self >= 0x80 { return false; }
2688 match ASCII_CHARACTER_CLASS
[*self as usize] {
2689 Ux
| U
| Lx
| L
| D
| P
=> true,
2694 /// Checks if the value is an ASCII whitespace character:
2695 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
2696 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
2698 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
2699 /// whitespace][infra-aw]. There are several other definitions in
2700 /// wide use. For instance, [the POSIX locale][pct] includes
2701 /// U+000B VERTICAL TAB as well as all the above characters,
2702 /// but—from the very same specification—[the default rule for
2703 /// "field splitting" in the Bourne shell][bfs] considers *only*
2704 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
2706 /// If you are writing a program that will process an existing
2707 /// file format, check what that format's definition of whitespace is
2708 /// before using this function.
2710 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
2711 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
2712 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
2717 /// #![feature(ascii_ctype)]
2719 /// let uppercase_a = b'A';
2720 /// let uppercase_g = b'G';
2723 /// let zero = b'0';
2724 /// let percent = b'%';
2725 /// let space = b' ';
2727 /// let esc = 0x1b_u8;
2729 /// assert!(!uppercase_a.is_ascii_whitespace());
2730 /// assert!(!uppercase_g.is_ascii_whitespace());
2731 /// assert!(!a.is_ascii_whitespace());
2732 /// assert!(!g.is_ascii_whitespace());
2733 /// assert!(!zero.is_ascii_whitespace());
2734 /// assert!(!percent.is_ascii_whitespace());
2735 /// assert!(space.is_ascii_whitespace());
2736 /// assert!(lf.is_ascii_whitespace());
2737 /// assert!(!esc.is_ascii_whitespace());
2739 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2741 pub fn is_ascii_whitespace(&self) -> bool
{
2742 if *self >= 0x80 { return false; }
2743 match ASCII_CHARACTER_CLASS
[*self as usize] {
2749 /// Checks if the value is an ASCII control character:
2750 /// U+0000 NUL ... U+001F UNIT SEPARATOR, or U+007F DELETE.
2751 /// Note that most ASCII whitespace characters are control
2752 /// characters, but SPACE is not.
2757 /// #![feature(ascii_ctype)]
2759 /// let uppercase_a = b'A';
2760 /// let uppercase_g = b'G';
2763 /// let zero = b'0';
2764 /// let percent = b'%';
2765 /// let space = b' ';
2767 /// let esc = 0x1b_u8;
2769 /// assert!(!uppercase_a.is_ascii_control());
2770 /// assert!(!uppercase_g.is_ascii_control());
2771 /// assert!(!a.is_ascii_control());
2772 /// assert!(!g.is_ascii_control());
2773 /// assert!(!zero.is_ascii_control());
2774 /// assert!(!percent.is_ascii_control());
2775 /// assert!(!space.is_ascii_control());
2776 /// assert!(lf.is_ascii_control());
2777 /// assert!(esc.is_ascii_control());
2779 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2781 pub fn is_ascii_control(&self) -> bool
{
2782 if *self >= 0x80 { return false; }
2783 match ASCII_CHARACTER_CLASS
[*self as usize] {
2792 uint_impl
! { u16, u16, 16 }
2797 uint_impl
! { u32, u32, 32 }
2802 uint_impl
! { u64, u64, 64 }
2807 uint_impl
! { u128, u128, 128 }
2810 #[cfg(target_pointer_width = "16")]
2813 uint_impl
! { usize, u16, 16 }
2815 #[cfg(target_pointer_width = "32")]
2818 uint_impl
! { usize, u32, 32 }
2821 #[cfg(target_pointer_width = "64")]
2824 uint_impl
! { usize, u64, 64 }
2827 /// A classification of floating point numbers.
2829 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
2830 /// their documentation for more.
2832 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
2833 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
2838 /// use std::num::FpCategory;
2841 /// let num = 12.4_f32;
2842 /// let inf = f32::INFINITY;
2843 /// let zero = 0f32;
2844 /// let sub: f32 = 1.1754942e-38;
2845 /// let nan = f32::NAN;
2847 /// assert_eq!(num.classify(), FpCategory::Normal);
2848 /// assert_eq!(inf.classify(), FpCategory::Infinite);
2849 /// assert_eq!(zero.classify(), FpCategory::Zero);
2850 /// assert_eq!(nan.classify(), FpCategory::Nan);
2851 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
2853 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2854 #[stable(feature = "rust1", since = "1.0.0")]
2855 pub enum FpCategory
{
2856 /// "Not a Number", often obtained by dividing by zero.
2857 #[stable(feature = "rust1", since = "1.0.0")]
2860 /// Positive or negative infinity.
2861 #[stable(feature = "rust1", since = "1.0.0")]
2864 /// Positive or negative zero.
2865 #[stable(feature = "rust1", since = "1.0.0")]
2868 /// De-normalized floating point representation (less precise than `Normal`).
2869 #[stable(feature = "rust1", since = "1.0.0")]
2872 /// A regular floating point number.
2873 #[stable(feature = "rust1", since = "1.0.0")]
2877 /// A built-in floating point number.
2879 #[unstable(feature = "core_float",
2880 reason
= "stable interface is via `impl f{32,64}` in later crates",
2882 pub trait Float
: Sized
{
2883 /// Type used by `to_bits` and `from_bits`.
2884 #[stable(feature = "core_float_bits", since = "1.24.0")]
2887 /// Returns `true` if this value is NaN and false otherwise.
2888 #[stable(feature = "core", since = "1.6.0")]
2889 fn is_nan(self) -> bool
;
2890 /// Returns `true` if this value is positive infinity or negative infinity and
2891 /// false otherwise.
2892 #[stable(feature = "core", since = "1.6.0")]
2893 fn is_infinite(self) -> bool
;
2894 /// Returns `true` if this number is neither infinite nor NaN.
2895 #[stable(feature = "core", since = "1.6.0")]
2896 fn is_finite(self) -> bool
;
2897 /// Returns `true` if this number is neither zero, infinite, denormal, or NaN.
2898 #[stable(feature = "core", since = "1.6.0")]
2899 fn is_normal(self) -> bool
;
2900 /// Returns the category that this number falls into.
2901 #[stable(feature = "core", since = "1.6.0")]
2902 fn classify(self) -> FpCategory
;
2904 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
2905 /// number is `Float::nan()`.
2906 #[stable(feature = "core", since = "1.6.0")]
2907 fn abs(self) -> Self;
2908 /// Returns a number that represents the sign of `self`.
2910 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
2911 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
2912 /// - `Float::nan()` if the number is `Float::nan()`
2913 #[stable(feature = "core", since = "1.6.0")]
2914 fn signum(self) -> Self;
2916 /// Returns `true` if `self` is positive, including `+0.0` and
2917 /// `Float::infinity()`.
2918 #[stable(feature = "core", since = "1.6.0")]
2919 fn is_sign_positive(self) -> bool
;
2920 /// Returns `true` if `self` is negative, including `-0.0` and
2921 /// `Float::neg_infinity()`.
2922 #[stable(feature = "core", since = "1.6.0")]
2923 fn is_sign_negative(self) -> bool
;
2925 /// Take the reciprocal (inverse) of a number, `1/x`.
2926 #[stable(feature = "core", since = "1.6.0")]
2927 fn recip(self) -> Self;
2929 /// Raise a number to an integer power.
2931 /// Using this function is generally faster than using `powf`
2932 #[stable(feature = "core", since = "1.6.0")]
2933 fn powi(self, n
: i32) -> Self;
2935 /// Convert radians to degrees.
2936 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
2937 fn to_degrees(self) -> Self;
2938 /// Convert degrees to radians.
2939 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
2940 fn to_radians(self) -> Self;
2942 /// Returns the maximum of the two numbers.
2943 #[stable(feature = "core_float_min_max", since="1.20.0")]
2944 fn max(self, other
: Self) -> Self;
2945 /// Returns the minimum of the two numbers.
2946 #[stable(feature = "core_float_min_max", since="1.20.0")]
2947 fn min(self, other
: Self) -> Self;
2949 /// Raw transmutation to integer.
2950 #[stable(feature = "core_float_bits", since="1.24.0")]
2951 fn to_bits(self) -> Self::Bits
;
2952 /// Raw transmutation from integer.
2953 #[stable(feature = "core_float_bits", since="1.24.0")]
2954 fn from_bits(v
: Self::Bits
) -> Self;
2957 macro_rules
! from_str_radix_int_impl
{
2959 #[stable(feature = "rust1", since = "1.0.0")]
2960 impl FromStr
for $t
{
2961 type Err
= ParseIntError
;
2962 fn from_str(src
: &str) -> Result
<Self, ParseIntError
> {
2963 from_str_radix(src
, 10)
2968 from_str_radix_int_impl
! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
2970 /// The error type returned when a checked integral type conversion fails.
2971 #[unstable(feature = "try_from", issue = "33417")]
2972 #[derive(Debug, Copy, Clone)]
2973 pub struct TryFromIntError(());
2975 impl TryFromIntError
{
2976 #[unstable(feature = "int_error_internals",
2977 reason
= "available through Error trait and this method should \
2978 not be exposed publicly",
2981 pub fn __description(&self) -> &str {
2982 "out of range integral type conversion attempted"
2986 #[unstable(feature = "try_from", issue = "33417")]
2987 impl fmt
::Display
for TryFromIntError
{
2988 fn fmt(&self, fmt
: &mut fmt
::Formatter
) -> fmt
::Result
{
2989 self.__description().fmt(fmt
)
2993 #[unstable(feature = "try_from", issue = "33417")]
2994 impl From
<Infallible
> for TryFromIntError
{
2995 fn from(infallible
: Infallible
) -> TryFromIntError
{
3001 // no possible bounds violation
3002 macro_rules
! try_from_unbounded
{
3003 ($source
:ty
, $
($target
:ty
),*) => {$
(
3004 #[unstable(feature = "try_from", issue = "33417")]
3005 impl TryFrom
<$source
> for $target
{
3006 type Error
= Infallible
;
3009 fn try_from(value
: $source
) -> Result
<Self, Self::Error
> {
3010 Ok(value
as $target
)
3016 // only negative bounds
3017 macro_rules
! try_from_lower_bounded
{
3018 ($source
:ty
, $
($target
:ty
),*) => {$
(
3019 #[unstable(feature = "try_from", issue = "33417")]
3020 impl TryFrom
<$source
> for $target
{
3021 type Error
= TryFromIntError
;
3024 fn try_from(u
: $source
) -> Result
<$target
, TryFromIntError
> {
3028 Err(TryFromIntError(()))
3035 // unsigned to signed (only positive bound)
3036 macro_rules
! try_from_upper_bounded
{
3037 ($source
:ty
, $
($target
:ty
),*) => {$
(
3038 #[unstable(feature = "try_from", issue = "33417")]
3039 impl TryFrom
<$source
> for $target
{
3040 type Error
= TryFromIntError
;
3043 fn try_from(u
: $source
) -> Result
<$target
, TryFromIntError
> {
3044 if u
> (<$target
>::max_value() as $source
) {
3045 Err(TryFromIntError(()))
3055 macro_rules
! try_from_both_bounded
{
3056 ($source
:ty
, $
($target
:ty
),*) => {$
(
3057 #[unstable(feature = "try_from", issue = "33417")]
3058 impl TryFrom
<$source
> for $target
{
3059 type Error
= TryFromIntError
;
3062 fn try_from(u
: $source
) -> Result
<$target
, TryFromIntError
> {
3063 let min
= <$target
>::min_value() as $source
;
3064 let max
= <$target
>::max_value() as $source
;
3065 if u
< min
|| u
> max
{
3066 Err(TryFromIntError(()))
3076 ($mac
:ident
, $source
:ty
, $
($target
:ty
),*) => {$
(
3077 $mac
!($target
, $source
);
3081 /// intra-sign conversions
3082 try_from_upper_bounded
!(u16, u8);
3083 try_from_upper_bounded
!(u32, u16, u8);
3084 try_from_upper_bounded
!(u64, u32, u16, u8);
3085 try_from_upper_bounded
!(u128
, u64, u32, u16, u8);
3087 try_from_both_bounded
!(i16, i8);
3088 try_from_both_bounded
!(i32, i16, i8);
3089 try_from_both_bounded
!(i64, i32, i16, i8);
3090 try_from_both_bounded
!(i128
, i64, i32, i16, i8);
3092 // unsigned-to-signed
3093 try_from_upper_bounded
!(u8, i8);
3094 try_from_upper_bounded
!(u16, i8, i16);
3095 try_from_upper_bounded
!(u32, i8, i16, i32);
3096 try_from_upper_bounded
!(u64, i8, i16, i32, i64);
3097 try_from_upper_bounded
!(u128
, i8, i16, i32, i64, i128
);
3099 // signed-to-unsigned
3100 try_from_lower_bounded
!(i8, u8, u16, u32, u64, u128
);
3101 try_from_lower_bounded
!(i16, u16, u32, u64, u128
);
3102 try_from_lower_bounded
!(i32, u32, u64, u128
);
3103 try_from_lower_bounded
!(i64, u64, u128
);
3104 try_from_lower_bounded
!(i128
, u128
);
3105 try_from_both_bounded
!(i16, u8);
3106 try_from_both_bounded
!(i32, u16, u8);
3107 try_from_both_bounded
!(i64, u32, u16, u8);
3108 try_from_both_bounded
!(i128
, u64, u32, u16, u8);
3111 try_from_upper_bounded
!(usize, isize);
3112 try_from_lower_bounded
!(isize, usize);
3114 #[cfg(target_pointer_width = "16")]
3115 mod ptr_try_from_impls
{
3116 use super::TryFromIntError
;
3117 use convert
::{Infallible, TryFrom}
;
3119 try_from_upper_bounded
!(usize, u8);
3120 try_from_unbounded
!(usize, u16, u32, u64, u128
);
3121 try_from_upper_bounded
!(usize, i8, i16);
3122 try_from_unbounded
!(usize, i32, i64, i128
);
3124 try_from_both_bounded
!(isize, u8);
3125 try_from_lower_bounded
!(isize, u16, u32, u64, u128
);
3126 try_from_both_bounded
!(isize, i8);
3127 try_from_unbounded
!(isize, i16, i32, i64, i128
);
3129 rev
!(try_from_unbounded
, usize, u16);
3130 rev
!(try_from_upper_bounded
, usize, u32, u64, u128
);
3131 rev
!(try_from_lower_bounded
, usize, i8, i16);
3132 rev
!(try_from_both_bounded
, usize, i32, i64, i128
);
3134 rev
!(try_from_unbounded
, isize, u8);
3135 rev
!(try_from_upper_bounded
, isize, u16, u32, u64, u128
);
3136 rev
!(try_from_unbounded
, isize, i16);
3137 rev
!(try_from_both_bounded
, isize, i32, i64, i128
);
3140 #[cfg(target_pointer_width = "32")]
3141 mod ptr_try_from_impls
{
3142 use super::TryFromIntError
;
3143 use convert
::{Infallible, TryFrom}
;
3145 try_from_upper_bounded
!(usize, u8, u16);
3146 try_from_unbounded
!(usize, u32, u64, u128
);
3147 try_from_upper_bounded
!(usize, i8, i16, i32);
3148 try_from_unbounded
!(usize, i64, i128
);
3150 try_from_both_bounded
!(isize, u8, u16);
3151 try_from_lower_bounded
!(isize, u32, u64, u128
);
3152 try_from_both_bounded
!(isize, i8, i16);
3153 try_from_unbounded
!(isize, i32, i64, i128
);
3155 rev
!(try_from_unbounded
, usize, u16, u32);
3156 rev
!(try_from_upper_bounded
, usize, u64, u128
);
3157 rev
!(try_from_lower_bounded
, usize, i8, i16, i32);
3158 rev
!(try_from_both_bounded
, usize, i64, i128
);
3160 rev
!(try_from_unbounded
, isize, u8, u16);
3161 rev
!(try_from_upper_bounded
, isize, u32, u64, u128
);
3162 rev
!(try_from_unbounded
, isize, i16, i32);
3163 rev
!(try_from_both_bounded
, isize, i64, i128
);
3166 #[cfg(target_pointer_width = "64")]
3167 mod ptr_try_from_impls
{
3168 use super::TryFromIntError
;
3169 use convert
::{Infallible, TryFrom}
;
3171 try_from_upper_bounded
!(usize, u8, u16, u32);
3172 try_from_unbounded
!(usize, u64, u128
);
3173 try_from_upper_bounded
!(usize, i8, i16, i32, i64);
3174 try_from_unbounded
!(usize, i128
);
3176 try_from_both_bounded
!(isize, u8, u16, u32);
3177 try_from_lower_bounded
!(isize, u64, u128
);
3178 try_from_both_bounded
!(isize, i8, i16, i32);
3179 try_from_unbounded
!(isize, i64, i128
);
3181 rev
!(try_from_unbounded
, usize, u16, u32, u64);
3182 rev
!(try_from_upper_bounded
, usize, u128
);
3183 rev
!(try_from_lower_bounded
, usize, i8, i16, i32, i64);
3184 rev
!(try_from_both_bounded
, usize, i128
);
3186 rev
!(try_from_unbounded
, isize, u8, u16, u32);
3187 rev
!(try_from_upper_bounded
, isize, u64, u128
);
3188 rev
!(try_from_unbounded
, isize, i16, i32, i64);
3189 rev
!(try_from_both_bounded
, isize, i128
);
3193 trait FromStrRadixHelper
: PartialOrd
+ Copy
{
3194 fn min_value() -> Self;
3195 fn max_value() -> Self;
3196 fn from_u32(u
: u32) -> Self;
3197 fn checked_mul(&self, other
: u32) -> Option
<Self>;
3198 fn checked_sub(&self, other
: u32) -> Option
<Self>;
3199 fn checked_add(&self, other
: u32) -> Option
<Self>;
3203 ($
($t
:ty
)*) => ($
(impl FromStrRadixHelper
for $t
{
3205 fn min_value() -> Self { Self::min_value() }
3207 fn max_value() -> Self { Self::max_value() }
3209 fn from_u32(u
: u32) -> Self { u as Self }
3211 fn checked_mul(&self, other
: u32) -> Option
<Self> {
3212 Self::checked_mul(*self, other
as Self)
3215 fn checked_sub(&self, other
: u32) -> Option
<Self> {
3216 Self::checked_sub(*self, other
as Self)
3219 fn checked_add(&self, other
: u32) -> Option
<Self> {
3220 Self::checked_add(*self, other
as Self)
3224 doit
! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
3226 fn from_str_radix
<T
: FromStrRadixHelper
>(src
: &str, radix
: u32) -> Result
<T
, ParseIntError
> {
3227 use self::IntErrorKind
::*;
3228 use self::ParseIntError
as PIE
;
3230 assert
!(radix
>= 2 && radix
<= 36,
3231 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
3235 return Err(PIE { kind: Empty }
);
3238 let is_signed_ty
= T
::from_u32(0) > T
::min_value();
3240 // all valid digits are ascii, so we will just iterate over the utf8 bytes
3241 // and cast them to chars. .to_digit() will safely return None for anything
3242 // other than a valid ascii digit for the given radix, including the first-byte
3243 // of multi-byte sequences
3244 let src
= src
.as_bytes();
3246 let (is_positive
, digits
) = match src
[0] {
3247 b'
+'
=> (true, &src
[1..]),
3248 b'
-'
if is_signed_ty
=> (false, &src
[1..]),
3252 if digits
.is_empty() {
3253 return Err(PIE { kind: Empty }
);
3256 let mut result
= T
::from_u32(0);
3258 // The number is positive
3260 let x
= match (c
as char).to_digit(radix
) {
3262 None
=> return Err(PIE { kind: InvalidDigit }
),
3264 result
= match result
.checked_mul(radix
) {
3265 Some(result
) => result
,
3266 None
=> return Err(PIE { kind: Overflow }
),
3268 result
= match result
.checked_add(x
) {
3269 Some(result
) => result
,
3270 None
=> return Err(PIE { kind: Overflow }
),
3274 // The number is negative
3276 let x
= match (c
as char).to_digit(radix
) {
3278 None
=> return Err(PIE { kind: InvalidDigit }
),
3280 result
= match result
.checked_mul(radix
) {
3281 Some(result
) => result
,
3282 None
=> return Err(PIE { kind: Underflow }
),
3284 result
= match result
.checked_sub(x
) {
3285 Some(result
) => result
,
3286 None
=> return Err(PIE { kind: Underflow }
),
3293 /// An error which can be returned when parsing an integer.
3295 /// This error is used as the error type for the `from_str_radix()` functions
3296 /// on the primitive integer types, such as [`i8::from_str_radix`].
3298 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
3299 #[derive(Debug, Clone, PartialEq, Eq)]
3300 #[stable(feature = "rust1", since = "1.0.0")]
3301 pub struct ParseIntError
{
3305 #[derive(Debug, Clone, PartialEq, Eq)]
3313 impl ParseIntError
{
3314 #[unstable(feature = "int_error_internals",
3315 reason
= "available through Error trait and this method should \
3316 not be exposed publicly",
3319 pub fn __description(&self) -> &str {
3321 IntErrorKind
::Empty
=> "cannot parse integer from empty string",
3322 IntErrorKind
::InvalidDigit
=> "invalid digit found in string",
3323 IntErrorKind
::Overflow
=> "number too large to fit in target type",
3324 IntErrorKind
::Underflow
=> "number too small to fit in target type",
3329 #[stable(feature = "rust1", since = "1.0.0")]
3330 impl fmt
::Display
for ParseIntError
{
3331 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
3332 self.__description().fmt(f
)
3336 #[stable(feature = "rust1", since = "1.0.0")]
3337 pub use num
::dec2flt
::ParseFloatError
;
3339 // Conversion traits for primitive integer and float types
3340 // Conversions T -> T are covered by a blanket impl and therefore excluded
3341 // Some conversions from and to usize/isize are not implemented due to portability concerns
3342 macro_rules
! impl_from
{
3343 ($Small
: ty
, $Large
: ty
, #[$attr:meta]) => {
3345 impl From
<$Small
> for $Large
{
3347 fn from(small
: $Small
) -> $Large
{
3354 // Unsigned -> Unsigned
3355 impl_from
! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3356 impl_from
! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3357 impl_from
! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3358 impl_from
! { u8, u128, #[unstable(feature = "i128", issue = "35118")] }
3359 impl_from
! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3360 impl_from
! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3361 impl_from
! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3362 impl_from
! { u16, u128, #[unstable(feature = "i128", issue = "35118")] }
3363 impl_from
! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3364 impl_from
! { u32, u128, #[unstable(feature = "i128", issue = "35118")] }
3365 impl_from
! { u64, u128, #[unstable(feature = "i128", issue = "35118")] }
3368 impl_from
! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3369 impl_from
! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3370 impl_from
! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3371 impl_from
! { i8, i128, #[unstable(feature = "i128", issue = "35118")] }
3372 impl_from
! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3373 impl_from
! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3374 impl_from
! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3375 impl_from
! { i16, i128, #[unstable(feature = "i128", issue = "35118")] }
3376 impl_from
! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3377 impl_from
! { i32, i128, #[unstable(feature = "i128", issue = "35118")] }
3378 impl_from
! { i64, i128, #[unstable(feature = "i128", issue = "35118")] }
3380 // Unsigned -> Signed
3381 impl_from
! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3382 impl_from
! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3383 impl_from
! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3384 impl_from
! { u8, i128, #[unstable(feature = "i128", issue = "35118")] }
3385 impl_from
! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3386 impl_from
! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3387 impl_from
! { u16, i128, #[unstable(feature = "i128", issue = "35118")] }
3388 impl_from
! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3389 impl_from
! { u32, i128, #[unstable(feature = "i128", issue = "35118")] }
3390 impl_from
! { u64, i128, #[unstable(feature = "i128", issue = "35118")] }
3392 // Note: integers can only be represented with full precision in a float if
3393 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
3394 // Lossy float conversions are not implemented at this time.
3397 impl_from
! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3398 impl_from
! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3399 impl_from
! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3400 impl_from
! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3401 impl_from
! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3403 // Unsigned -> Float
3404 impl_from
! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3405 impl_from
! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3406 impl_from
! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3407 impl_from
! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3408 impl_from
! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3411 impl_from
! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3413 static ASCII_LOWERCASE_MAP
: [u8; 256] = [
3414 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
3415 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
3416 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
3417 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
3418 b' '
, b'
!'
, b'
"', b'#', b'$', b'%', b'&', b'\'',
3419 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
3420 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
3421 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
3424 b'a', b'b', b'c', b'd', b'e', b'f', b'g',
3425 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
3426 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
3429 b'[', b'\\', b']', b'^', b'_',
3430 b'`', b'a', b'b', b'c', b'd', b'e', b'f', b'g',
3431 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
3432 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
3433 b'x', b'y', b'z', b'{', b'|', b'}', b'~', 0x7f,
3434 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
3435 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
3436 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
3437 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
3438 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
3439 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
3440 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
3441 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
3442 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
3443 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
3444 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
3445 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
3446 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
3447 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
3448 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
3449 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
3452 static ASCII_UPPERCASE_MAP: [u8; 256] = [
3453 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
3454 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
3455 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
3456 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
3457 b' ', b'!', b'"'
, b'
#', b'$', b'%', b'&', b'\'',
3458 b'
('
, b'
)'
, b'
*'
, b'
+'
, b'
,'
, b'
-'
, b'
.'
, b'
/'
,
3459 b'
0'
, b'
1'
, b'
2'
, b'
3'
, b'
4'
, b'
5'
, b'
6'
, b'
7'
,
3460 b'
8'
, b'
9'
, b'
:'
, b'
;'
, b'
<'
, b'
='
, b'
>'
, b'?'
,
3461 b'@'
, b'A'
, b'B'
, b'C'
, b'D'
, b'E'
, b'F'
, b'G'
,
3462 b'H'
, b'I'
, b'J'
, b'K'
, b'L'
, b'M'
, b'N'
, b'O'
,
3463 b'P'
, b'Q'
, b'R'
, b'S'
, b'T'
, b'U'
, b'V'
, b'W'
,
3464 b'X'
, b'Y'
, b'Z'
, b'
['
, b'
\\'
, b'
]'
, b'
^', b'_'
,
3467 b'A'
, b'B'
, b'C'
, b'D'
, b'E'
, b'F'
, b'G'
,
3468 b'H'
, b'I'
, b'J'
, b'K'
, b'L'
, b'M'
, b'N'
, b'O'
,
3469 b'P'
, b'Q'
, b'R'
, b'S'
, b'T'
, b'U'
, b'V'
, b'W'
,
3472 b'{', b'|', b'}'
, b'
~'
, 0x7f,
3473 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
3474 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
3475 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
3476 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
3477 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
3478 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
3479 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
3480 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
3481 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
3482 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
3483 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
3484 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
3485 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
3486 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
3487 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
3488 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
3491 enum AsciiCharacterClass
{
3493 Cw
, // control whitespace
3497 Lx
, // lowercase hex digit
3499 Ux
, // uppercase hex digit
3502 use self::AsciiCharacterClass
::*;
3504 static ASCII_CHARACTER_CLASS
: [AsciiCharacterClass
; 128] = [
3505 // _0 _1 _2 _3 _4 _5 _6 _7 _8 _9 _a _b _c _d _e _f
3506 C
, C
, C
, C
, C
, C
, C
, C
, C
, Cw
,Cw
,C
, Cw
,Cw
,C
, C
, // 0_
3507 C
, C
, C
, C
, C
, C
, C
, C
, C
, C
, C
, C
, C
, C
, C
, C
, // 1_
3508 W
, P
, P
, P
, P
, P
, P
, P
, P
, P
, P
, P
, P
, P
, P
, P
, // 2_
3509 D
, D
, D
, D
, D
, D
, D
, D
, D
, D
, P
, P
, P
, P
, P
, P
, // 3_
3510 P
, Ux
,Ux
,Ux
,Ux
,Ux
,Ux
,U
, U
, U
, U
, U
, U
, U
, U
, U
, // 4_
3511 U
, U
, U
, U
, U
, U
, U
, U
, U
, U
, U
, P
, P
, P
, P
, P
, // 5_
3512 P
, Lx
,Lx
,Lx
,Lx
,Lx
,Lx
,L
, L
, L
, L
, L
, L
, L
, L
, L
, // 6_
3513 L
, L
, L
, L
, L
, L
, L
, L
, L
, L
, L
, P
, P
, P
, P
, C
, // 7_