1 macro_rules! uint_impl {
2 ($SelfT:ty, $ActualT:ident, $SignedT:ident, $BITS:expr, $MaxV:expr,
3 $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
4 $reversed:expr, $le_bytes:expr, $be_bytes:expr,
5 $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
6 /// The smallest value that can be represented by this integer type.
13 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN, 0);")]
15 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
16 pub const MIN: Self = 0;
18 /// The largest value that can be represented by this integer type,
19 #[doc = concat!("2<sup>", $BITS, "</sup> - 1.")]
26 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($MaxV), ");")]
28 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
29 pub const MAX: Self = !0;
31 /// The size of this integer type in bits.
36 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::BITS, ", stringify!($BITS), ");")]
38 #[stable(feature = "int_bits_const", since = "1.53.0")]
39 pub const BITS: u32 = $BITS;
41 /// Converts a string slice in a given base to an integer.
43 /// The string is expected to be an optional `+` sign
44 /// followed by digits.
45 /// Leading and trailing whitespace represent an error.
46 /// Digits are a subset of these characters, depending on `radix`:
54 /// This function panics if `radix` is not in the range from 2 to 36.
61 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));")]
63 #[stable(feature = "rust1", since = "1.0.0")]
64 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
65 from_str_radix(src, radix)
68 /// Returns the number of ones in the binary representation of `self`.
75 #[doc = concat!("let n = 0b01001100", stringify!($SelfT), ";")]
77 /// assert_eq!(n.count_ones(), 3);
79 #[stable(feature = "rust1", since = "1.0.0")]
80 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
81 #[doc(alias = "popcount")]
82 #[doc(alias = "popcnt")]
83 #[must_use = "this returns the result of the operation, \
84 without modifying the original"]
86 pub const fn count_ones(self) -> u32 {
87 intrinsics::ctpop(self as $ActualT) as u32
90 /// Returns the number of zeros in the binary representation of `self`.
97 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.count_zeros(), 0);")]
99 #[stable(feature = "rust1", since = "1.0.0")]
100 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
101 #[must_use = "this returns the result of the operation, \
102 without modifying the original"]
104 pub const fn count_zeros(self) -> u32 {
108 /// Returns the number of leading zeros in the binary representation of `self`.
115 #[doc = concat!("let n = ", stringify!($SelfT), "::MAX >> 2;")]
117 /// assert_eq!(n.leading_zeros(), 2);
119 #[stable(feature = "rust1", since = "1.0.0")]
120 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
121 #[must_use = "this returns the result of the operation, \
122 without modifying the original"]
124 pub const fn leading_zeros(self) -> u32 {
125 intrinsics::ctlz(self as $ActualT) as u32
128 /// Returns the number of trailing zeros in the binary representation
136 #[doc = concat!("let n = 0b0101000", stringify!($SelfT), ";")]
138 /// assert_eq!(n.trailing_zeros(), 3);
140 #[stable(feature = "rust1", since = "1.0.0")]
141 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
142 #[must_use = "this returns the result of the operation, \
143 without modifying the original"]
145 pub const fn trailing_zeros(self) -> u32 {
146 intrinsics::cttz(self) as u32
149 /// Returns the number of leading ones in the binary representation of `self`.
156 #[doc = concat!("let n = !(", stringify!($SelfT), "::MAX >> 2);")]
158 /// assert_eq!(n.leading_ones(), 2);
160 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
161 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
162 #[must_use = "this returns the result of the operation, \
163 without modifying the original"]
165 pub const fn leading_ones(self) -> u32 {
166 (!self).leading_zeros()
169 /// Returns the number of trailing ones in the binary representation
177 #[doc = concat!("let n = 0b1010111", stringify!($SelfT), ";")]
179 /// assert_eq!(n.trailing_ones(), 3);
181 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
182 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
183 #[must_use = "this returns the result of the operation, \
184 without modifying the original"]
186 pub const fn trailing_ones(self) -> u32 {
187 (!self).trailing_zeros()
190 /// Shifts the bits to the left by a specified amount, `n`,
191 /// wrapping the truncated bits to the end of the resulting integer.
193 /// Please note this isn't the same operation as the `<<` shifting operator!
200 #[doc = concat!("let n = ", $rot_op, stringify!($SelfT), ";")]
201 #[doc = concat!("let m = ", $rot_result, ";")]
203 #[doc = concat!("assert_eq!(n.rotate_left(", $rot, "), m);")]
205 #[stable(feature = "rust1", since = "1.0.0")]
206 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
207 #[must_use = "this returns the result of the operation, \
208 without modifying the original"]
210 pub const fn rotate_left(self, n: u32) -> Self {
211 intrinsics::rotate_left(self, n as $SelfT)
214 /// Shifts the bits to the right by a specified amount, `n`,
215 /// wrapping the truncated bits to the beginning of the resulting
218 /// Please note this isn't the same operation as the `>>` shifting operator!
225 #[doc = concat!("let n = ", $rot_result, stringify!($SelfT), ";")]
226 #[doc = concat!("let m = ", $rot_op, ";")]
228 #[doc = concat!("assert_eq!(n.rotate_right(", $rot, "), m);")]
230 #[stable(feature = "rust1", since = "1.0.0")]
231 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
232 #[must_use = "this returns the result of the operation, \
233 without modifying the original"]
235 pub const fn rotate_right(self, n: u32) -> Self {
236 intrinsics::rotate_right(self, n as $SelfT)
239 /// Reverses the byte order of the integer.
246 #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
247 /// let m = n.swap_bytes();
249 #[doc = concat!("assert_eq!(m, ", $swapped, ");")]
251 #[stable(feature = "rust1", since = "1.0.0")]
252 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
253 #[must_use = "this returns the result of the operation, \
254 without modifying the original"]
256 pub const fn swap_bytes(self) -> Self {
257 intrinsics::bswap(self as $ActualT) as Self
260 /// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
261 /// second least-significant bit becomes second most-significant bit, etc.
268 #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
269 /// let m = n.reverse_bits();
271 #[doc = concat!("assert_eq!(m, ", $reversed, ");")]
272 #[doc = concat!("assert_eq!(0, 0", stringify!($SelfT), ".reverse_bits());")]
274 #[stable(feature = "reverse_bits", since = "1.37.0")]
275 #[rustc_const_stable(feature = "const_math", since = "1.37.0")]
276 #[must_use = "this returns the result of the operation, \
277 without modifying the original"]
279 pub const fn reverse_bits(self) -> Self {
280 intrinsics::bitreverse(self as $ActualT) as Self
283 /// Converts an integer from big endian to the target's endianness.
285 /// On big endian this is a no-op. On little endian the bytes are
293 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
295 /// if cfg!(target_endian = "big") {
296 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_be(n), n)")]
298 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())")]
301 #[stable(feature = "rust1", since = "1.0.0")]
302 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
305 pub const fn from_be(x: Self) -> Self {
306 #[cfg(target_endian = "big")]
310 #[cfg(not(target_endian = "big"))]
316 /// Converts an integer from little endian to the target's endianness.
318 /// On little endian this is a no-op. On big endian the bytes are
326 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
328 /// if cfg!(target_endian = "little") {
329 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_le(n), n)")]
331 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())")]
334 #[stable(feature = "rust1", since = "1.0.0")]
335 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
338 pub const fn from_le(x: Self) -> Self {
339 #[cfg(target_endian = "little")]
343 #[cfg(not(target_endian = "little"))]
349 /// Converts `self` to big endian from the target's endianness.
351 /// On big endian this is a no-op. On little endian the bytes are
359 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
361 /// if cfg!(target_endian = "big") {
362 /// assert_eq!(n.to_be(), n)
364 /// assert_eq!(n.to_be(), n.swap_bytes())
367 #[stable(feature = "rust1", since = "1.0.0")]
368 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
369 #[must_use = "this returns the result of the operation, \
370 without modifying the original"]
372 pub const fn to_be(self) -> Self { // or not to be?
373 #[cfg(target_endian = "big")]
377 #[cfg(not(target_endian = "big"))]
383 /// Converts `self` to little endian from the target's endianness.
385 /// On little endian this is a no-op. On big endian the bytes are
393 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
395 /// if cfg!(target_endian = "little") {
396 /// assert_eq!(n.to_le(), n)
398 /// assert_eq!(n.to_le(), n.swap_bytes())
401 #[stable(feature = "rust1", since = "1.0.0")]
402 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
403 #[must_use = "this returns the result of the operation, \
404 without modifying the original"]
406 pub const fn to_le(self) -> Self {
407 #[cfg(target_endian = "little")]
411 #[cfg(not(target_endian = "little"))]
417 /// Checked integer addition. Computes `self + rhs`, returning `None`
418 /// if overflow occurred.
426 "assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(1), ",
427 "Some(", stringify!($SelfT), "::MAX - 1));"
429 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);")]
431 #[stable(feature = "rust1", since = "1.0.0")]
432 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
433 #[must_use = "this returns the result of the operation, \
434 without modifying the original"]
436 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
437 let (a, b) = self.overflowing_add(rhs);
438 if unlikely!(b) {None} else {Some(a)}
441 /// Unchecked integer addition. Computes `self + rhs`, assuming overflow
446 /// This results in undefined behavior when
447 #[doc = concat!("`self + rhs > ", stringify!($SelfT), "::MAX` or `self + rhs < ", stringify!($SelfT), "::MIN`,")]
448 /// i.e. when [`checked_add`] would return `None`.
450 #[doc = concat!("[`checked_add`]: ", stringify!($SelfT), "::checked_add")]
452 feature = "unchecked_math",
453 reason = "niche optimization path",
456 #[must_use = "this returns the result of the operation, \
457 without modifying the original"]
458 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
460 pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
461 // SAFETY: the caller must uphold the safety contract for
463 unsafe { intrinsics::unchecked_add(self, rhs) }
466 /// Checked addition with a signed integer. Computes `self + rhs`,
467 /// returning `None` if overflow occurred.
474 /// # #![feature(mixed_integer_ops)]
475 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_add_signed(2), Some(3));")]
476 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_add_signed(-2), None);")]
477 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add_signed(3), None);")]
479 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
480 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
481 #[must_use = "this returns the result of the operation, \
482 without modifying the original"]
484 pub const fn checked_add_signed(self, rhs: $SignedT) -> Option<Self> {
485 let (a, b) = self.overflowing_add_signed(rhs);
486 if unlikely!(b) {None} else {Some(a)}
489 /// Checked integer subtraction. Computes `self - rhs`, returning
490 /// `None` if overflow occurred.
497 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));")]
498 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);")]
500 #[stable(feature = "rust1", since = "1.0.0")]
501 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
502 #[must_use = "this returns the result of the operation, \
503 without modifying the original"]
505 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
506 let (a, b) = self.overflowing_sub(rhs);
507 if unlikely!(b) {None} else {Some(a)}
510 /// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
515 /// This results in undefined behavior when
516 #[doc = concat!("`self - rhs > ", stringify!($SelfT), "::MAX` or `self - rhs < ", stringify!($SelfT), "::MIN`,")]
517 /// i.e. when [`checked_sub`] would return `None`.
519 #[doc = concat!("[`checked_sub`]: ", stringify!($SelfT), "::checked_sub")]
521 feature = "unchecked_math",
522 reason = "niche optimization path",
525 #[must_use = "this returns the result of the operation, \
526 without modifying the original"]
527 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
529 pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
530 // SAFETY: the caller must uphold the safety contract for
532 unsafe { intrinsics::unchecked_sub(self, rhs) }
535 /// Checked integer multiplication. Computes `self * rhs`, returning
536 /// `None` if overflow occurred.
543 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));")]
544 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);")]
546 #[stable(feature = "rust1", since = "1.0.0")]
547 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
548 #[must_use = "this returns the result of the operation, \
549 without modifying the original"]
551 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
552 let (a, b) = self.overflowing_mul(rhs);
553 if unlikely!(b) {None} else {Some(a)}
556 /// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
561 /// This results in undefined behavior when
562 #[doc = concat!("`self * rhs > ", stringify!($SelfT), "::MAX` or `self * rhs < ", stringify!($SelfT), "::MIN`,")]
563 /// i.e. when [`checked_mul`] would return `None`.
565 #[doc = concat!("[`checked_mul`]: ", stringify!($SelfT), "::checked_mul")]
567 feature = "unchecked_math",
568 reason = "niche optimization path",
571 #[must_use = "this returns the result of the operation, \
572 without modifying the original"]
573 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
575 pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
576 // SAFETY: the caller must uphold the safety contract for
578 unsafe { intrinsics::unchecked_mul(self, rhs) }
581 /// Checked integer division. Computes `self / rhs`, returning `None`
589 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));")]
590 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);")]
592 #[stable(feature = "rust1", since = "1.0.0")]
593 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.52.0")]
594 #[must_use = "this returns the result of the operation, \
595 without modifying the original"]
597 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
598 if unlikely!(rhs == 0) {
601 // SAFETY: div by zero has been checked above and unsigned types have no other
602 // failure modes for division
603 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
607 /// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
615 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));")]
616 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);")]
618 #[stable(feature = "euclidean_division", since = "1.38.0")]
619 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
620 #[must_use = "this returns the result of the operation, \
621 without modifying the original"]
623 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
624 if unlikely!(rhs == 0) {
627 Some(self.div_euclid(rhs))
632 /// Checked integer remainder. Computes `self % rhs`, returning `None`
640 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));")]
641 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);")]
643 #[stable(feature = "wrapping", since = "1.7.0")]
644 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.52.0")]
645 #[must_use = "this returns the result of the operation, \
646 without modifying the original"]
648 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
649 if unlikely!(rhs == 0) {
652 // SAFETY: div by zero has been checked above and unsigned types have no other
653 // failure modes for division
654 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
658 /// Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
666 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));")]
667 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);")]
669 #[stable(feature = "euclidean_division", since = "1.38.0")]
670 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
671 #[must_use = "this returns the result of the operation, \
672 without modifying the original"]
674 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
675 if unlikely!(rhs == 0) {
678 Some(self.rem_euclid(rhs))
682 /// Returns the logarithm of the number with respect to an arbitrary base,
685 /// This method might not be optimized owing to implementation details;
686 /// `log2` can produce results more efficiently for base 2, and `log10`
687 /// can produce results more efficiently for base 10.
691 /// When the number is negative, zero, or if the base is not at least 2;
692 /// it panics in debug mode and the return value is 0 in release mode.
697 /// #![feature(int_log)]
698 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".log(5), 1);")]
700 #[unstable(feature = "int_log", issue = "70887")]
701 #[must_use = "this returns the result of the operation, \
702 without modifying the original"]
705 #[rustc_inherit_overflow_checks]
706 #[allow(arithmetic_overflow)]
707 pub const fn log(self, base: Self) -> u32 {
708 match self.checked_log(base) {
711 // In debug builds, trigger a panic on None.
712 // This should optimize completely out in release builds.
713 let _ = Self::MAX + 1;
720 /// Returns the base 2 logarithm of the number, rounded down.
724 /// When the number is negative or zero it panics in debug mode and
725 /// the return value is 0 in release mode.
730 /// #![feature(int_log)]
731 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".log2(), 1);")]
733 #[unstable(feature = "int_log", issue = "70887")]
734 #[must_use = "this returns the result of the operation, \
735 without modifying the original"]
738 #[rustc_inherit_overflow_checks]
739 #[allow(arithmetic_overflow)]
740 pub const fn log2(self) -> u32 {
741 match self.checked_log2() {
744 // In debug builds, trigger a panic on None.
745 // This should optimize completely out in release builds.
746 let _ = Self::MAX + 1;
753 /// Returns the base 10 logarithm of the number, rounded down.
757 /// When the number is negative or zero it panics in debug mode and the
758 /// return value is 0 in release mode.
763 /// #![feature(int_log)]
764 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".log10(), 1);")]
766 #[unstable(feature = "int_log", issue = "70887")]
767 #[must_use = "this returns the result of the operation, \
768 without modifying the original"]
771 #[rustc_inherit_overflow_checks]
772 #[allow(arithmetic_overflow)]
773 pub const fn log10(self) -> u32 {
774 match self.checked_log10() {
777 // In debug builds, trigger a panic on None.
778 // This should optimize completely out in release builds.
779 let _ = Self::MAX + 1;
786 /// Returns the logarithm of the number with respect to an arbitrary base,
789 /// Returns `None` if the number is zero, or if the base is not at least 2.
791 /// This method might not be optimized owing to implementation details;
792 /// `checked_log2` can produce results more efficiently for base 2, and
793 /// `checked_log10` can produce results more efficiently for base 10.
798 /// #![feature(int_log)]
799 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_log(5), Some(1));")]
801 #[unstable(feature = "int_log", issue = "70887")]
802 #[must_use = "this returns the result of the operation, \
803 without modifying the original"]
805 pub const fn checked_log(self, base: Self) -> Option<u32> {
806 if self <= 0 || base <= 1 {
812 // Optimization for 128 bit wide integers.
813 if Self::BITS == 128 {
814 let b = Self::log2(self) / (Self::log2(base) + 1);
816 r /= base.pow(b as u32);
827 /// Returns the base 2 logarithm of the number, rounded down.
829 /// Returns `None` if the number is zero.
834 /// #![feature(int_log)]
835 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_log2(), Some(1));")]
837 #[unstable(feature = "int_log", issue = "70887")]
838 #[must_use = "this returns the result of the operation, \
839 without modifying the original"]
841 pub const fn checked_log2(self) -> Option<u32> {
845 // SAFETY: We just checked that this number is positive
846 let log = (Self::BITS - 1) - unsafe { intrinsics::ctlz_nonzero(self) as u32 };
851 /// Returns the base 10 logarithm of the number, rounded down.
853 /// Returns `None` if the number is zero.
858 /// #![feature(int_log)]
859 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_log10(), Some(1));")]
861 #[unstable(feature = "int_log", issue = "70887")]
862 #[must_use = "this returns the result of the operation, \
863 without modifying the original"]
865 pub const fn checked_log10(self) -> Option<u32> {
866 int_log10::$ActualT(self as $ActualT)
869 /// Checked negation. Computes `-self`, returning `None` unless `self ==
872 /// Note that negating any positive integer will overflow.
879 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));")]
880 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);")]
882 #[stable(feature = "wrapping", since = "1.7.0")]
883 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
884 #[must_use = "this returns the result of the operation, \
885 without modifying the original"]
887 pub const fn checked_neg(self) -> Option<Self> {
888 let (a, b) = self.overflowing_neg();
889 if unlikely!(b) {None} else {Some(a)}
892 /// Checked shift left. Computes `self << rhs`, returning `None`
893 /// if `rhs` is larger than or equal to the number of bits in `self`.
900 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));")]
901 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);")]
903 #[stable(feature = "wrapping", since = "1.7.0")]
904 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
905 #[must_use = "this returns the result of the operation, \
906 without modifying the original"]
908 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
909 let (a, b) = self.overflowing_shl(rhs);
910 if unlikely!(b) {None} else {Some(a)}
913 /// Unchecked shift left. Computes `self << rhs`, assuming that
914 /// `rhs` is less than the number of bits in `self`.
918 /// This results in undefined behavior if `rhs` is larger than
919 /// or equal to the number of bits in `self`,
920 /// i.e. when [`checked_shl`] would return `None`.
922 #[doc = concat!("[`checked_shl`]: ", stringify!($SelfT), "::checked_shl")]
924 feature = "unchecked_math",
925 reason = "niche optimization path",
928 #[must_use = "this returns the result of the operation, \
929 without modifying the original"]
930 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
932 pub const unsafe fn unchecked_shl(self, rhs: Self) -> Self {
933 // SAFETY: the caller must uphold the safety contract for
935 unsafe { intrinsics::unchecked_shl(self, rhs) }
938 /// Checked shift right. Computes `self >> rhs`, returning `None`
939 /// if `rhs` is larger than or equal to the number of bits in `self`.
946 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));")]
947 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);")]
949 #[stable(feature = "wrapping", since = "1.7.0")]
950 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
951 #[must_use = "this returns the result of the operation, \
952 without modifying the original"]
954 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
955 let (a, b) = self.overflowing_shr(rhs);
956 if unlikely!(b) {None} else {Some(a)}
959 /// Unchecked shift right. Computes `self >> rhs`, assuming that
960 /// `rhs` is less than the number of bits in `self`.
964 /// This results in undefined behavior if `rhs` is larger than
965 /// or equal to the number of bits in `self`,
966 /// i.e. when [`checked_shr`] would return `None`.
968 #[doc = concat!("[`checked_shr`]: ", stringify!($SelfT), "::checked_shr")]
970 feature = "unchecked_math",
971 reason = "niche optimization path",
974 #[must_use = "this returns the result of the operation, \
975 without modifying the original"]
976 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
978 pub const unsafe fn unchecked_shr(self, rhs: Self) -> Self {
979 // SAFETY: the caller must uphold the safety contract for
981 unsafe { intrinsics::unchecked_shr(self, rhs) }
984 /// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
985 /// overflow occurred.
992 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));")]
993 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);")]
995 #[stable(feature = "no_panic_pow", since = "1.34.0")]
996 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
997 #[must_use = "this returns the result of the operation, \
998 without modifying the original"]
1000 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
1004 let mut base = self;
1005 let mut acc: Self = 1;
1009 acc = try_opt!(acc.checked_mul(base));
1012 base = try_opt!(base.checked_mul(base));
1015 // since exp!=0, finally the exp must be 1.
1016 // Deal with the final bit of the exponent separately, since
1017 // squaring the base afterwards is not necessary and may cause a
1018 // needless overflow.
1020 Some(try_opt!(acc.checked_mul(base)))
1023 /// Saturating integer addition. Computes `self + rhs`, saturating at
1024 /// the numeric bounds instead of overflowing.
1031 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);")]
1032 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(127), ", stringify!($SelfT), "::MAX);")]
1034 #[stable(feature = "rust1", since = "1.0.0")]
1035 #[must_use = "this returns the result of the operation, \
1036 without modifying the original"]
1037 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1039 pub const fn saturating_add(self, rhs: Self) -> Self {
1040 intrinsics::saturating_add(self, rhs)
1043 /// Saturating addition with a signed integer. Computes `self + rhs`,
1044 /// saturating at the numeric bounds instead of overflowing.
1051 /// # #![feature(mixed_integer_ops)]
1052 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_signed(2), 3);")]
1053 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_signed(-2), 0);")]
1054 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).saturating_add_signed(4), ", stringify!($SelfT), "::MAX);")]
1056 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1057 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1058 #[must_use = "this returns the result of the operation, \
1059 without modifying the original"]
1061 pub const fn saturating_add_signed(self, rhs: $SignedT) -> Self {
1062 let (res, overflow) = self.overflowing_add(rhs as Self);
1063 if overflow == (rhs < 0) {
1065 } else if overflow {
1072 /// Saturating integer subtraction. Computes `self - rhs`, saturating
1073 /// at the numeric bounds instead of overflowing.
1080 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);")]
1081 #[doc = concat!("assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);")]
1083 #[stable(feature = "rust1", since = "1.0.0")]
1084 #[must_use = "this returns the result of the operation, \
1085 without modifying the original"]
1086 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1088 pub const fn saturating_sub(self, rhs: Self) -> Self {
1089 intrinsics::saturating_sub(self, rhs)
1092 /// Saturating integer multiplication. Computes `self * rhs`,
1093 /// saturating at the numeric bounds instead of overflowing.
1100 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);")]
1101 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),"::MAX);")]
1103 #[stable(feature = "wrapping", since = "1.7.0")]
1104 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1105 #[must_use = "this returns the result of the operation, \
1106 without modifying the original"]
1108 pub const fn saturating_mul(self, rhs: Self) -> Self {
1109 match self.checked_mul(rhs) {
1115 /// Saturating integer division. Computes `self / rhs`, saturating at the
1116 /// numeric bounds instead of overflowing.
1123 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".saturating_div(2), 2);")]
1128 #[doc = concat!("let _ = 1", stringify!($SelfT), ".saturating_div(0);")]
1131 #[stable(feature = "saturating_div", since = "1.58.0")]
1132 #[must_use = "this returns the result of the operation, \
1133 without modifying the original"]
1135 pub const fn saturating_div(self, rhs: Self) -> Self {
1136 // on unsigned types, there is no overflow in integer division
1137 self.wrapping_div(rhs)
1140 /// Saturating integer exponentiation. Computes `self.pow(exp)`,
1141 /// saturating at the numeric bounds instead of overflowing.
1148 #[doc = concat!("assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);")]
1149 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);")]
1151 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1152 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1153 #[must_use = "this returns the result of the operation, \
1154 without modifying the original"]
1156 pub const fn saturating_pow(self, exp: u32) -> Self {
1157 match self.checked_pow(exp) {
1163 /// Wrapping (modular) addition. Computes `self + rhs`,
1164 /// wrapping around at the boundary of the type.
1171 #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);")]
1172 #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);")]
1174 #[stable(feature = "rust1", since = "1.0.0")]
1175 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1176 #[must_use = "this returns the result of the operation, \
1177 without modifying the original"]
1179 pub const fn wrapping_add(self, rhs: Self) -> Self {
1180 intrinsics::wrapping_add(self, rhs)
1183 /// Wrapping (modular) addition with a signed integer. Computes
1184 /// `self + rhs`, wrapping around at the boundary of the type.
1191 /// # #![feature(mixed_integer_ops)]
1192 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_add_signed(2), 3);")]
1193 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_add_signed(-2), ", stringify!($SelfT), "::MAX);")]
1194 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).wrapping_add_signed(4), 1);")]
1196 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1197 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1198 #[must_use = "this returns the result of the operation, \
1199 without modifying the original"]
1201 pub const fn wrapping_add_signed(self, rhs: $SignedT) -> Self {
1202 self.wrapping_add(rhs as Self)
1205 /// Wrapping (modular) subtraction. Computes `self - rhs`,
1206 /// wrapping around at the boundary of the type.
1213 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);")]
1214 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::MAX), 101);")]
1216 #[stable(feature = "rust1", since = "1.0.0")]
1217 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1218 #[must_use = "this returns the result of the operation, \
1219 without modifying the original"]
1221 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1222 intrinsics::wrapping_sub(self, rhs)
1225 /// Wrapping (modular) multiplication. Computes `self *
1226 /// rhs`, wrapping around at the boundary of the type.
1232 /// Please note that this example is shared between integer types.
1233 /// Which explains why `u8` is used here.
1236 /// assert_eq!(10u8.wrapping_mul(12), 120);
1237 /// assert_eq!(25u8.wrapping_mul(12), 44);
1239 #[stable(feature = "rust1", since = "1.0.0")]
1240 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1241 #[must_use = "this returns the result of the operation, \
1242 without modifying the original"]
1244 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1245 intrinsics::wrapping_mul(self, rhs)
1248 /// Wrapping (modular) division. Computes `self / rhs`.
1249 /// Wrapped division on unsigned types is just normal division.
1250 /// There's no way wrapping could ever happen.
1251 /// This function exists, so that all operations
1252 /// are accounted for in the wrapping operations.
1259 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);")]
1261 #[stable(feature = "num_wrapping", since = "1.2.0")]
1262 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1263 #[must_use = "this returns the result of the operation, \
1264 without modifying the original"]
1266 pub const fn wrapping_div(self, rhs: Self) -> Self {
1270 /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
1271 /// Wrapped division on unsigned types is just normal division.
1272 /// There's no way wrapping could ever happen.
1273 /// This function exists, so that all operations
1274 /// are accounted for in the wrapping operations.
1275 /// Since, for the positive integers, all common
1276 /// definitions of division are equal, this
1277 /// is exactly equal to `self.wrapping_div(rhs)`.
1284 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);")]
1286 #[stable(feature = "euclidean_division", since = "1.38.0")]
1287 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1288 #[must_use = "this returns the result of the operation, \
1289 without modifying the original"]
1291 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
1295 /// Wrapping (modular) remainder. Computes `self % rhs`.
1296 /// Wrapped remainder calculation on unsigned types is
1297 /// just the regular remainder calculation.
1298 /// There's no way wrapping could ever happen.
1299 /// This function exists, so that all operations
1300 /// are accounted for in the wrapping operations.
1307 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);")]
1309 #[stable(feature = "num_wrapping", since = "1.2.0")]
1310 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1311 #[must_use = "this returns the result of the operation, \
1312 without modifying the original"]
1314 pub const fn wrapping_rem(self, rhs: Self) -> Self {
1318 /// Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
1319 /// Wrapped modulo calculation on unsigned types is
1320 /// just the regular remainder calculation.
1321 /// There's no way wrapping could ever happen.
1322 /// This function exists, so that all operations
1323 /// are accounted for in the wrapping operations.
1324 /// Since, for the positive integers, all common
1325 /// definitions of division are equal, this
1326 /// is exactly equal to `self.wrapping_rem(rhs)`.
1333 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);")]
1335 #[stable(feature = "euclidean_division", since = "1.38.0")]
1336 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1337 #[must_use = "this returns the result of the operation, \
1338 without modifying the original"]
1340 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1344 /// Wrapping (modular) negation. Computes `-self`,
1345 /// wrapping around at the boundary of the type.
1347 /// Since unsigned types do not have negative equivalents
1348 /// all applications of this function will wrap (except for `-0`).
1349 /// For values smaller than the corresponding signed type's maximum
1350 /// the result is the same as casting the corresponding signed value.
1351 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
1352 /// `MAX` is the corresponding signed type's maximum.
1358 /// Please note that this example is shared between integer types.
1359 /// Which explains why `i8` is used here.
1362 /// assert_eq!(100i8.wrapping_neg(), -100);
1363 /// assert_eq!((-128i8).wrapping_neg(), -128);
1365 #[stable(feature = "num_wrapping", since = "1.2.0")]
1366 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1367 #[must_use = "this returns the result of the operation, \
1368 without modifying the original"]
1370 pub const fn wrapping_neg(self) -> Self {
1371 (0 as $SelfT).wrapping_sub(self)
1374 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1375 /// where `mask` removes any high-order bits of `rhs` that
1376 /// would cause the shift to exceed the bitwidth of the type.
1378 /// Note that this is *not* the same as a rotate-left; the
1379 /// RHS of a wrapping shift-left is restricted to the range
1380 /// of the type, rather than the bits shifted out of the LHS
1381 /// being returned to the other end. The primitive integer
1382 /// types all implement a [`rotate_left`](Self::rotate_left) function,
1383 /// which may be what you want instead.
1390 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);")]
1391 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);")]
1393 #[stable(feature = "num_wrapping", since = "1.2.0")]
1394 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1395 #[must_use = "this returns the result of the operation, \
1396 without modifying the original"]
1398 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1399 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1402 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1406 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
1407 /// where `mask` removes any high-order bits of `rhs` that
1408 /// would cause the shift to exceed the bitwidth of the type.
1410 /// Note that this is *not* the same as a rotate-right; the
1411 /// RHS of a wrapping shift-right is restricted to the range
1412 /// of the type, rather than the bits shifted out of the LHS
1413 /// being returned to the other end. The primitive integer
1414 /// types all implement a [`rotate_right`](Self::rotate_right) function,
1415 /// which may be what you want instead.
1422 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);")]
1423 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);")]
1425 #[stable(feature = "num_wrapping", since = "1.2.0")]
1426 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1427 #[must_use = "this returns the result of the operation, \
1428 without modifying the original"]
1430 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1431 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1434 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1438 /// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1439 /// wrapping around at the boundary of the type.
1446 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);")]
1447 /// assert_eq!(3u8.wrapping_pow(6), 217);
1449 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1450 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1451 #[must_use = "this returns the result of the operation, \
1452 without modifying the original"]
1454 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
1458 let mut base = self;
1459 let mut acc: Self = 1;
1463 acc = acc.wrapping_mul(base);
1466 base = base.wrapping_mul(base);
1469 // since exp!=0, finally the exp must be 1.
1470 // Deal with the final bit of the exponent separately, since
1471 // squaring the base afterwards is not necessary and may cause a
1472 // needless overflow.
1473 acc.wrapping_mul(base)
1476 /// Calculates `self` + `rhs`
1478 /// Returns a tuple of the addition along with a boolean indicating
1479 /// whether an arithmetic overflow would occur. If an overflow would
1480 /// have occurred then the wrapped value is returned.
1488 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));")]
1489 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));")]
1491 #[stable(feature = "wrapping", since = "1.7.0")]
1492 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1493 #[must_use = "this returns the result of the operation, \
1494 without modifying the original"]
1496 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1497 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1501 /// Calculates `self + rhs + carry` without the ability to overflow.
1503 /// Performs "ternary addition" which takes in an extra bit to add, and may return an
1504 /// additional bit of overflow. This allows for chaining together multiple additions
1505 /// to create "big integers" which represent larger values.
1512 /// #![feature(bigint_helper_methods)]
1513 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".carrying_add(2, false), (7, false));")]
1514 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".carrying_add(2, true), (8, false));")]
1515 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.carrying_add(1, false), (0, true));")]
1516 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.carrying_add(1, true), (1, true));")]
1518 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
1519 #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")]
1520 #[must_use = "this returns the result of the operation, \
1521 without modifying the original"]
1523 pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
1524 // note: longer-term this should be done via an intrinsic, but this has been shown
1525 // to generate optimal code for now, and LLVM doesn't have an equivalent intrinsic
1526 let (a, b) = self.overflowing_add(rhs);
1527 let (c, d) = a.overflowing_add(carry as $SelfT);
1531 /// Calculates `self` + `rhs` with a signed `rhs`
1533 /// Returns a tuple of the addition along with a boolean indicating
1534 /// whether an arithmetic overflow would occur. If an overflow would
1535 /// have occurred then the wrapped value is returned.
1542 /// # #![feature(mixed_integer_ops)]
1543 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_signed(2), (3, false));")]
1544 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_signed(-2), (", stringify!($SelfT), "::MAX, true));")]
1545 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).overflowing_add_signed(4), (1, true));")]
1547 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1548 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1549 #[must_use = "this returns the result of the operation, \
1550 without modifying the original"]
1552 pub const fn overflowing_add_signed(self, rhs: $SignedT) -> (Self, bool) {
1553 let (res, overflowed) = self.overflowing_add(rhs as Self);
1554 (res, overflowed ^ (rhs < 0))
1557 /// Calculates `self` - `rhs`
1559 /// Returns a tuple of the subtraction along with a boolean indicating
1560 /// whether an arithmetic overflow would occur. If an overflow would
1561 /// have occurred then the wrapped value is returned.
1569 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));")]
1570 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")]
1572 #[stable(feature = "wrapping", since = "1.7.0")]
1573 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1574 #[must_use = "this returns the result of the operation, \
1575 without modifying the original"]
1577 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1578 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1582 /// Calculates `self - rhs - borrow` without the ability to overflow.
1584 /// Performs "ternary subtraction" which takes in an extra bit to subtract, and may return
1585 /// an additional bit of overflow. This allows for chaining together multiple subtractions
1586 /// to create "big integers" which represent larger values.
1593 /// #![feature(bigint_helper_methods)]
1594 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".borrowing_sub(2, false), (3, false));")]
1595 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".borrowing_sub(2, true), (2, false));")]
1596 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".borrowing_sub(1, false), (", stringify!($SelfT), "::MAX, true));")]
1597 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".borrowing_sub(1, true), (", stringify!($SelfT), "::MAX - 1, true));")]
1599 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
1600 #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")]
1601 #[must_use = "this returns the result of the operation, \
1602 without modifying the original"]
1604 pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
1605 // note: longer-term this should be done via an intrinsic, but this has been shown
1606 // to generate optimal code for now, and LLVM doesn't have an equivalent intrinsic
1607 let (a, b) = self.overflowing_sub(rhs);
1608 let (c, d) = a.overflowing_sub(borrow as $SelfT);
1612 /// Computes the absolute difference between `self` and `other`.
1619 /// #![feature(int_abs_diff)]
1620 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(80), 20", stringify!($SelfT), ");")]
1621 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(110), 10", stringify!($SelfT), ");")]
1623 #[unstable(feature = "int_abs_diff", issue = "89492")]
1624 #[must_use = "this returns the result of the operation, \
1625 without modifying the original"]
1627 pub const fn abs_diff(self, other: Self) -> Self {
1628 if mem::size_of::<Self>() == 1 {
1629 // Trick LLVM into generating the psadbw instruction when SSE2
1630 // is available and this function is autovectorized for u8's.
1631 (self as i32).wrapping_sub(other as i32).abs() as Self
1641 /// Calculates the multiplication of `self` and `rhs`.
1643 /// Returns a tuple of the multiplication along with a boolean
1644 /// indicating whether an arithmetic overflow would occur. If an
1645 /// overflow would have occurred then the wrapped value is returned.
1651 /// Please note that this example is shared between integer types.
1652 /// Which explains why `u32` is used here.
1655 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
1656 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
1658 #[stable(feature = "wrapping", since = "1.7.0")]
1659 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1660 #[must_use = "this returns the result of the operation, \
1661 without modifying the original"]
1663 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1664 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1668 /// Calculates the divisor when `self` is divided by `rhs`.
1670 /// Returns a tuple of the divisor along with a boolean indicating
1671 /// whether an arithmetic overflow would occur. Note that for unsigned
1672 /// integers overflow never occurs, so the second value is always
1677 /// This function will panic if `rhs` is 0.
1684 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));")]
1687 #[stable(feature = "wrapping", since = "1.7.0")]
1688 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1689 #[must_use = "this returns the result of the operation, \
1690 without modifying the original"]
1691 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1695 /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1697 /// Returns a tuple of the divisor along with a boolean indicating
1698 /// whether an arithmetic overflow would occur. Note that for unsigned
1699 /// integers overflow never occurs, so the second value is always
1701 /// Since, for the positive integers, all common
1702 /// definitions of division are equal, this
1703 /// is exactly equal to `self.overflowing_div(rhs)`.
1707 /// This function will panic if `rhs` is 0.
1714 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));")]
1717 #[stable(feature = "euclidean_division", since = "1.38.0")]
1718 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1719 #[must_use = "this returns the result of the operation, \
1720 without modifying the original"]
1721 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1725 /// Calculates the remainder when `self` is divided by `rhs`.
1727 /// Returns a tuple of the remainder after dividing along with a boolean
1728 /// indicating whether an arithmetic overflow would occur. Note that for
1729 /// unsigned integers overflow never occurs, so the second value is
1734 /// This function will panic if `rhs` is 0.
1741 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));")]
1744 #[stable(feature = "wrapping", since = "1.7.0")]
1745 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1746 #[must_use = "this returns the result of the operation, \
1747 without modifying the original"]
1748 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1752 /// Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
1754 /// Returns a tuple of the modulo after dividing along with a boolean
1755 /// indicating whether an arithmetic overflow would occur. Note that for
1756 /// unsigned integers overflow never occurs, so the second value is
1758 /// Since, for the positive integers, all common
1759 /// definitions of division are equal, this operation
1760 /// is exactly equal to `self.overflowing_rem(rhs)`.
1764 /// This function will panic if `rhs` is 0.
1771 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));")]
1774 #[stable(feature = "euclidean_division", since = "1.38.0")]
1775 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1776 #[must_use = "this returns the result of the operation, \
1777 without modifying the original"]
1778 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1782 /// Negates self in an overflowing fashion.
1784 /// Returns `!self + 1` using wrapping operations to return the value
1785 /// that represents the negation of this unsigned value. Note that for
1786 /// positive unsigned values overflow always occurs, but negating 0 does
1794 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));")]
1795 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT), ", true));")]
1798 #[stable(feature = "wrapping", since = "1.7.0")]
1799 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1800 #[must_use = "this returns the result of the operation, \
1801 without modifying the original"]
1802 pub const fn overflowing_neg(self) -> (Self, bool) {
1803 ((!self).wrapping_add(1), self != 0)
1806 /// Shifts self left by `rhs` bits.
1808 /// Returns a tuple of the shifted version of self along with a boolean
1809 /// indicating whether the shift value was larger than or equal to the
1810 /// number of bits. If the shift value is too large, then value is
1811 /// masked (N-1) where N is the number of bits, and this value is then
1812 /// used to perform the shift.
1819 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));")]
1820 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));")]
1822 #[stable(feature = "wrapping", since = "1.7.0")]
1823 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1824 #[must_use = "this returns the result of the operation, \
1825 without modifying the original"]
1827 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1828 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1831 /// Shifts self right by `rhs` bits.
1833 /// Returns a tuple of the shifted version of self along with a boolean
1834 /// indicating whether the shift value was larger than or equal to the
1835 /// number of bits. If the shift value is too large, then value is
1836 /// masked (N-1) where N is the number of bits, and this value is then
1837 /// used to perform the shift.
1844 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));")]
1845 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));")]
1847 #[stable(feature = "wrapping", since = "1.7.0")]
1848 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1849 #[must_use = "this returns the result of the operation, \
1850 without modifying the original"]
1852 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1853 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1856 /// Raises self to the power of `exp`, using exponentiation by squaring.
1858 /// Returns a tuple of the exponentiation along with a bool indicating
1859 /// whether an overflow happened.
1866 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));")]
1867 /// assert_eq!(3u8.overflowing_pow(6), (217, true));
1869 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1870 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1871 #[must_use = "this returns the result of the operation, \
1872 without modifying the original"]
1874 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1878 let mut base = self;
1879 let mut acc: Self = 1;
1880 let mut overflown = false;
1881 // Scratch space for storing results of overflowing_mul.
1886 r = acc.overflowing_mul(base);
1891 r = base.overflowing_mul(base);
1896 // since exp!=0, finally the exp must be 1.
1897 // Deal with the final bit of the exponent separately, since
1898 // squaring the base afterwards is not necessary and may cause a
1899 // needless overflow.
1900 r = acc.overflowing_mul(base);
1906 /// Raises self to the power of `exp`, using exponentiation by squaring.
1913 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".pow(5), 32);")]
1915 #[stable(feature = "rust1", since = "1.0.0")]
1916 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1917 #[must_use = "this returns the result of the operation, \
1918 without modifying the original"]
1920 #[rustc_inherit_overflow_checks]
1921 pub const fn pow(self, mut exp: u32) -> Self {
1925 let mut base = self;
1936 // since exp!=0, finally the exp must be 1.
1937 // Deal with the final bit of the exponent separately, since
1938 // squaring the base afterwards is not necessary and may cause a
1939 // needless overflow.
1943 /// Performs Euclidean division.
1945 /// Since, for the positive integers, all common
1946 /// definitions of division are equal, this
1947 /// is exactly equal to `self / rhs`.
1951 /// This function will panic if `rhs` is 0.
1958 #[doc = concat!("assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type")]
1960 #[stable(feature = "euclidean_division", since = "1.38.0")]
1961 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1962 #[must_use = "this returns the result of the operation, \
1963 without modifying the original"]
1965 #[rustc_inherit_overflow_checks]
1966 pub const fn div_euclid(self, rhs: Self) -> Self {
1971 /// Calculates the least remainder of `self (mod rhs)`.
1973 /// Since, for the positive integers, all common
1974 /// definitions of division are equal, this
1975 /// is exactly equal to `self % rhs`.
1979 /// This function will panic if `rhs` is 0.
1986 #[doc = concat!("assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type")]
1988 #[stable(feature = "euclidean_division", since = "1.38.0")]
1989 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1990 #[must_use = "this returns the result of the operation, \
1991 without modifying the original"]
1993 #[rustc_inherit_overflow_checks]
1994 pub const fn rem_euclid(self, rhs: Self) -> Self {
1998 /// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
2000 /// This is the same as performing `self / rhs` for all unsigned integers.
2004 /// This function will panic if `rhs` is 0.
2011 /// #![feature(int_roundings)]
2012 #[doc = concat!("assert_eq!(7_", stringify!($SelfT), ".unstable_div_floor(4), 1);")]
2014 #[unstable(feature = "int_roundings", issue = "88581")]
2015 #[must_use = "this returns the result of the operation, \
2016 without modifying the original"]
2018 #[rustc_inherit_overflow_checks]
2019 pub const fn unstable_div_floor(self, rhs: Self) -> Self {
2023 /// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
2027 /// This function will panic if `rhs` is 0.
2034 /// #![feature(int_roundings)]
2035 #[doc = concat!("assert_eq!(7_", stringify!($SelfT), ".unstable_div_ceil(4), 2);")]
2037 #[unstable(feature = "int_roundings", issue = "88581")]
2038 #[must_use = "this returns the result of the operation, \
2039 without modifying the original"]
2041 #[rustc_inherit_overflow_checks]
2042 pub const fn unstable_div_ceil(self, rhs: Self) -> Self {
2045 if r > 0 && rhs > 0 {
2052 /// Calculates the smallest value greater than or equal to `self` that
2053 /// is a multiple of `rhs`.
2057 /// This function will panic if `rhs` is 0 or the operation results in overflow.
2064 /// #![feature(int_roundings)]
2065 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".unstable_next_multiple_of(8), 16);")]
2066 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".unstable_next_multiple_of(8), 24);")]
2068 #[unstable(feature = "int_roundings", issue = "88581")]
2069 #[must_use = "this returns the result of the operation, \
2070 without modifying the original"]
2072 #[rustc_inherit_overflow_checks]
2073 pub const fn unstable_next_multiple_of(self, rhs: Self) -> Self {
2076 r => self + (rhs - r)
2080 /// Calculates the smallest value greater than or equal to `self` that
2081 /// is a multiple of `rhs`. Returns `None` is `rhs` is zero or the
2082 /// operation would result in overflow.
2089 /// #![feature(int_roundings)]
2090 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(16));")]
2091 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(24));")]
2092 #[doc = concat!("assert_eq!(1_", stringify!($SelfT), ".checked_next_multiple_of(0), None);")]
2093 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_multiple_of(2), None);")]
2095 #[unstable(feature = "int_roundings", issue = "88581")]
2096 #[must_use = "this returns the result of the operation, \
2097 without modifying the original"]
2099 #[rustc_inherit_overflow_checks]
2100 pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
2101 match try_opt!(self.checked_rem(rhs)) {
2103 r => self.checked_add(try_opt!(rhs.checked_sub(r)))
2107 /// Returns `true` if and only if `self == 2^k` for some `k`.
2114 #[doc = concat!("assert!(16", stringify!($SelfT), ".is_power_of_two());")]
2115 #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_power_of_two());")]
2118 #[stable(feature = "rust1", since = "1.0.0")]
2119 #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
2121 pub const fn is_power_of_two(self) -> bool {
2122 self.count_ones() == 1
2125 // Returns one less than next power of two.
2126 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
2128 // 8u8.one_less_than_next_power_of_two() == 7
2129 // 6u8.one_less_than_next_power_of_two() == 7
2131 // This method cannot overflow, as in the `next_power_of_two`
2132 // overflow cases it instead ends up returning the maximum value
2133 // of the type, and can return 0 for 0.
2135 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2136 const fn one_less_than_next_power_of_two(self) -> Self {
2137 if self <= 1 { return 0; }
2140 // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros.
2141 // That means the shift is always in-bounds, and some processors
2142 // (such as intel pre-haswell) have more efficient ctlz
2143 // intrinsics when the argument is non-zero.
2144 let z = unsafe { intrinsics::ctlz_nonzero(p) };
2148 /// Returns the smallest power of two greater than or equal to `self`.
2150 /// When return value overflows (i.e., `self > (1 << (N-1))` for type
2151 /// `uN`), it panics in debug mode and the return value is wrapped to 0 in
2152 /// release mode (the only situation in which method can return 0).
2159 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);")]
2160 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);")]
2162 #[stable(feature = "rust1", since = "1.0.0")]
2163 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2164 #[must_use = "this returns the result of the operation, \
2165 without modifying the original"]
2167 #[rustc_inherit_overflow_checks]
2168 pub const fn next_power_of_two(self) -> Self {
2169 self.one_less_than_next_power_of_two() + 1
2172 /// Returns the smallest power of two greater than or equal to `n`. If
2173 /// the next power of two is greater than the type's maximum value,
2174 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
2181 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_next_power_of_two(), Some(2));")]
2182 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));")]
2183 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_power_of_two(), None);")]
2186 #[stable(feature = "rust1", since = "1.0.0")]
2187 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2188 #[must_use = "this returns the result of the operation, \
2189 without modifying the original"]
2190 pub const fn checked_next_power_of_two(self) -> Option<Self> {
2191 self.one_less_than_next_power_of_two().checked_add(1)
2194 /// Returns the smallest power of two greater than or equal to `n`. If
2195 /// the next power of two is greater than the type's maximum value,
2196 /// the return value is wrapped to `0`.
2203 /// #![feature(wrapping_next_power_of_two)]
2205 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);")]
2206 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);")]
2207 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_next_power_of_two(), 0);")]
2209 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
2210 reason = "needs decision on wrapping behaviour")]
2211 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2212 #[must_use = "this returns the result of the operation, \
2213 without modifying the original"]
2214 pub const fn wrapping_next_power_of_two(self) -> Self {
2215 self.one_less_than_next_power_of_two().wrapping_add(1)
2218 /// Return the memory representation of this integer as a byte array in
2219 /// big-endian (network) byte order.
2221 #[doc = $to_xe_bytes_doc]
2226 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();")]
2227 #[doc = concat!("assert_eq!(bytes, ", $be_bytes, ");")]
2229 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2230 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2231 #[must_use = "this returns the result of the operation, \
2232 without modifying the original"]
2234 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2235 self.to_be().to_ne_bytes()
2238 /// Return the memory representation of this integer as a byte array in
2239 /// little-endian byte order.
2241 #[doc = $to_xe_bytes_doc]
2246 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();")]
2247 #[doc = concat!("assert_eq!(bytes, ", $le_bytes, ");")]
2249 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2250 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2251 #[must_use = "this returns the result of the operation, \
2252 without modifying the original"]
2254 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2255 self.to_le().to_ne_bytes()
2258 /// Return the memory representation of this integer as a byte array in
2259 /// native byte order.
2261 /// As the target platform's native endianness is used, portable code
2262 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2265 #[doc = $to_xe_bytes_doc]
2267 /// [`to_be_bytes`]: Self::to_be_bytes
2268 /// [`to_le_bytes`]: Self::to_le_bytes
2273 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();")]
2276 /// if cfg!(target_endian = "big") {
2277 #[doc = concat!(" ", $be_bytes)]
2279 #[doc = concat!(" ", $le_bytes)]
2283 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2284 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2285 #[must_use = "this returns the result of the operation, \
2286 without modifying the original"]
2287 // SAFETY: const sound because integers are plain old datatypes so we can always
2288 // transmute them to arrays of bytes
2290 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2291 // SAFETY: integers are plain old datatypes so we can always transmute them to
2293 unsafe { mem::transmute(self) }
2296 /// Create a native endian integer value from its representation
2297 /// as a byte array in big endian.
2299 #[doc = $from_xe_bytes_doc]
2304 #[doc = concat!("let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");")]
2305 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2308 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2311 /// use std::convert::TryInto;
2313 #[doc = concat!("fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2314 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2316 #[doc = concat!(" ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())")]
2319 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2320 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2323 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2324 Self::from_be(Self::from_ne_bytes(bytes))
2327 /// Create a native endian integer value from its representation
2328 /// as a byte array in little endian.
2330 #[doc = $from_xe_bytes_doc]
2335 #[doc = concat!("let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");")]
2336 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2339 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2342 /// use std::convert::TryInto;
2344 #[doc = concat!("fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2345 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2347 #[doc = concat!(" ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())")]
2350 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2351 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2354 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2355 Self::from_le(Self::from_ne_bytes(bytes))
2358 /// Create a native endian integer value from its memory representation
2359 /// as a byte array in native endianness.
2361 /// As the target platform's native endianness is used, portable code
2362 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2363 /// appropriate instead.
2365 /// [`from_be_bytes`]: Self::from_be_bytes
2366 /// [`from_le_bytes`]: Self::from_le_bytes
2368 #[doc = $from_xe_bytes_doc]
2373 #[doc = concat!("let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {")]
2374 #[doc = concat!(" ", $be_bytes, "")]
2376 #[doc = concat!(" ", $le_bytes, "")]
2378 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2381 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2384 /// use std::convert::TryInto;
2386 #[doc = concat!("fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2387 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2389 #[doc = concat!(" ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())")]
2392 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2393 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2395 // SAFETY: const sound because integers are plain old datatypes so we can always
2396 // transmute to them
2398 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2399 // SAFETY: integers are plain old datatypes so we can always transmute to them
2400 unsafe { mem::transmute(bytes) }
2403 /// New code should prefer to use
2404 #[doc = concat!("[`", stringify!($SelfT), "::MIN", "`] instead.")]
2406 /// Returns the smallest value that can be represented by this integer type.
2407 #[stable(feature = "rust1", since = "1.0.0")]
2410 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2411 #[rustc_deprecated(since = "TBD", reason = "replaced by the `MIN` associated constant on this type")]
2412 pub const fn min_value() -> Self { Self::MIN }
2414 /// New code should prefer to use
2415 #[doc = concat!("[`", stringify!($SelfT), "::MAX", "`] instead.")]
2417 /// Returns the largest value that can be represented by this integer type.
2418 #[stable(feature = "rust1", since = "1.0.0")]
2421 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2422 #[rustc_deprecated(since = "TBD", reason = "replaced by the `MAX` associated constant on this type")]
2423 pub const fn max_value() -> Self { Self::MAX }