1 macro_rules! uint_impl {
2 ($SelfT:ty, $ActualT:ident, $SignedT:ident, $NonZeroT:ident,
3 $BITS:expr, $MaxV:expr,
4 $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
5 $reversed:expr, $le_bytes:expr, $be_bytes:expr,
6 $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
7 /// The smallest value that can be represented by this integer type.
14 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN, 0);")]
16 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
17 pub const MIN: Self = 0;
19 /// The largest value that can be represented by this integer type,
20 #[doc = concat!("2<sup>", $BITS, "</sup> - 1.")]
27 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($MaxV), ");")]
29 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
30 pub const MAX: Self = !0;
32 /// The size of this integer type in bits.
37 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::BITS, ", stringify!($BITS), ");")]
39 #[stable(feature = "int_bits_const", since = "1.53.0")]
40 pub const BITS: u32 = $BITS;
42 /// Converts a string slice in a given base to an integer.
44 /// The string is expected to be an optional `+` sign
45 /// followed by digits.
46 /// Leading and trailing whitespace represent an error.
47 /// Digits are a subset of these characters, depending on `radix`:
55 /// This function panics if `radix` is not in the range from 2 to 36.
62 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));")]
64 #[stable(feature = "rust1", since = "1.0.0")]
65 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
66 from_str_radix(src, radix)
69 /// Returns the number of ones in the binary representation of `self`.
76 #[doc = concat!("let n = 0b01001100", stringify!($SelfT), ";")]
78 /// assert_eq!(n.count_ones(), 3);
80 #[stable(feature = "rust1", since = "1.0.0")]
81 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
82 #[doc(alias = "popcount")]
83 #[doc(alias = "popcnt")]
84 #[must_use = "this returns the result of the operation, \
85 without modifying the original"]
87 pub const fn count_ones(self) -> u32 {
88 intrinsics::ctpop(self as $ActualT) as u32
91 /// Returns the number of zeros in the binary representation of `self`.
98 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.count_zeros(), 0);")]
100 #[stable(feature = "rust1", since = "1.0.0")]
101 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
102 #[must_use = "this returns the result of the operation, \
103 without modifying the original"]
105 pub const fn count_zeros(self) -> u32 {
109 /// Returns the number of leading zeros in the binary representation of `self`.
116 #[doc = concat!("let n = ", stringify!($SelfT), "::MAX >> 2;")]
118 /// assert_eq!(n.leading_zeros(), 2);
120 #[stable(feature = "rust1", since = "1.0.0")]
121 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
122 #[must_use = "this returns the result of the operation, \
123 without modifying the original"]
125 pub const fn leading_zeros(self) -> u32 {
126 intrinsics::ctlz(self as $ActualT) as u32
129 /// Returns the number of trailing zeros in the binary representation
137 #[doc = concat!("let n = 0b0101000", stringify!($SelfT), ";")]
139 /// assert_eq!(n.trailing_zeros(), 3);
141 #[stable(feature = "rust1", since = "1.0.0")]
142 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
143 #[must_use = "this returns the result of the operation, \
144 without modifying the original"]
146 pub const fn trailing_zeros(self) -> u32 {
147 intrinsics::cttz(self) as u32
150 /// Returns the number of leading ones in the binary representation of `self`.
157 #[doc = concat!("let n = !(", stringify!($SelfT), "::MAX >> 2);")]
159 /// assert_eq!(n.leading_ones(), 2);
161 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
162 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
163 #[must_use = "this returns the result of the operation, \
164 without modifying the original"]
166 pub const fn leading_ones(self) -> u32 {
167 (!self).leading_zeros()
170 /// Returns the number of trailing ones in the binary representation
178 #[doc = concat!("let n = 0b1010111", stringify!($SelfT), ";")]
180 /// assert_eq!(n.trailing_ones(), 3);
182 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
183 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
184 #[must_use = "this returns the result of the operation, \
185 without modifying the original"]
187 pub const fn trailing_ones(self) -> u32 {
188 (!self).trailing_zeros()
191 /// Shifts the bits to the left by a specified amount, `n`,
192 /// wrapping the truncated bits to the end of the resulting integer.
194 /// Please note this isn't the same operation as the `<<` shifting operator!
201 #[doc = concat!("let n = ", $rot_op, stringify!($SelfT), ";")]
202 #[doc = concat!("let m = ", $rot_result, ";")]
204 #[doc = concat!("assert_eq!(n.rotate_left(", $rot, "), m);")]
206 #[stable(feature = "rust1", since = "1.0.0")]
207 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
208 #[must_use = "this returns the result of the operation, \
209 without modifying the original"]
211 pub const fn rotate_left(self, n: u32) -> Self {
212 intrinsics::rotate_left(self, n as $SelfT)
215 /// Shifts the bits to the right by a specified amount, `n`,
216 /// wrapping the truncated bits to the beginning of the resulting
219 /// Please note this isn't the same operation as the `>>` shifting operator!
226 #[doc = concat!("let n = ", $rot_result, stringify!($SelfT), ";")]
227 #[doc = concat!("let m = ", $rot_op, ";")]
229 #[doc = concat!("assert_eq!(n.rotate_right(", $rot, "), m);")]
231 #[stable(feature = "rust1", since = "1.0.0")]
232 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
233 #[must_use = "this returns the result of the operation, \
234 without modifying the original"]
236 pub const fn rotate_right(self, n: u32) -> Self {
237 intrinsics::rotate_right(self, n as $SelfT)
240 /// Reverses the byte order of the integer.
247 #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
248 /// let m = n.swap_bytes();
250 #[doc = concat!("assert_eq!(m, ", $swapped, ");")]
252 #[stable(feature = "rust1", since = "1.0.0")]
253 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
254 #[must_use = "this returns the result of the operation, \
255 without modifying the original"]
257 pub const fn swap_bytes(self) -> Self {
258 intrinsics::bswap(self as $ActualT) as Self
261 /// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
262 /// second least-significant bit becomes second most-significant bit, etc.
269 #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
270 /// let m = n.reverse_bits();
272 #[doc = concat!("assert_eq!(m, ", $reversed, ");")]
273 #[doc = concat!("assert_eq!(0, 0", stringify!($SelfT), ".reverse_bits());")]
275 #[stable(feature = "reverse_bits", since = "1.37.0")]
276 #[rustc_const_stable(feature = "const_math", since = "1.37.0")]
277 #[must_use = "this returns the result of the operation, \
278 without modifying the original"]
280 pub const fn reverse_bits(self) -> Self {
281 intrinsics::bitreverse(self as $ActualT) as Self
284 /// Converts an integer from big endian to the target's endianness.
286 /// On big endian this is a no-op. On little endian the bytes are
294 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
296 /// if cfg!(target_endian = "big") {
297 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_be(n), n)")]
299 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())")]
302 #[stable(feature = "rust1", since = "1.0.0")]
303 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
306 pub const fn from_be(x: Self) -> Self {
307 #[cfg(target_endian = "big")]
311 #[cfg(not(target_endian = "big"))]
317 /// Converts an integer from little endian to the target's endianness.
319 /// On little endian this is a no-op. On big endian the bytes are
327 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
329 /// if cfg!(target_endian = "little") {
330 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_le(n), n)")]
332 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())")]
335 #[stable(feature = "rust1", since = "1.0.0")]
336 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
339 pub const fn from_le(x: Self) -> Self {
340 #[cfg(target_endian = "little")]
344 #[cfg(not(target_endian = "little"))]
350 /// Converts `self` to big endian from the target's endianness.
352 /// On big endian this is a no-op. On little endian the bytes are
360 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
362 /// if cfg!(target_endian = "big") {
363 /// assert_eq!(n.to_be(), n)
365 /// assert_eq!(n.to_be(), n.swap_bytes())
368 #[stable(feature = "rust1", since = "1.0.0")]
369 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
370 #[must_use = "this returns the result of the operation, \
371 without modifying the original"]
373 pub const fn to_be(self) -> Self { // or not to be?
374 #[cfg(target_endian = "big")]
378 #[cfg(not(target_endian = "big"))]
384 /// Converts `self` to little endian from the target's endianness.
386 /// On little endian this is a no-op. On big endian the bytes are
394 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
396 /// if cfg!(target_endian = "little") {
397 /// assert_eq!(n.to_le(), n)
399 /// assert_eq!(n.to_le(), n.swap_bytes())
402 #[stable(feature = "rust1", since = "1.0.0")]
403 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
404 #[must_use = "this returns the result of the operation, \
405 without modifying the original"]
407 pub const fn to_le(self) -> Self {
408 #[cfg(target_endian = "little")]
412 #[cfg(not(target_endian = "little"))]
418 /// Checked integer addition. Computes `self + rhs`, returning `None`
419 /// if overflow occurred.
427 "assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(1), ",
428 "Some(", stringify!($SelfT), "::MAX - 1));"
430 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);")]
432 #[stable(feature = "rust1", since = "1.0.0")]
433 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
434 #[must_use = "this returns the result of the operation, \
435 without modifying the original"]
437 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
438 let (a, b) = self.overflowing_add(rhs);
439 if unlikely!(b) {None} else {Some(a)}
442 /// Unchecked integer addition. Computes `self + rhs`, assuming overflow
447 /// This results in undefined behavior when
448 #[doc = concat!("`self + rhs > ", stringify!($SelfT), "::MAX` or `self + rhs < ", stringify!($SelfT), "::MIN`,")]
449 /// i.e. when [`checked_add`] would return `None`.
451 #[doc = concat!("[`checked_add`]: ", stringify!($SelfT), "::checked_add")]
453 feature = "unchecked_math",
454 reason = "niche optimization path",
457 #[must_use = "this returns the result of the operation, \
458 without modifying the original"]
459 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
461 pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
462 // SAFETY: the caller must uphold the safety contract for
464 unsafe { intrinsics::unchecked_add(self, rhs) }
467 /// Checked addition with a signed integer. Computes `self + rhs`,
468 /// returning `None` if overflow occurred.
475 /// # #![feature(mixed_integer_ops)]
476 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_add_signed(2), Some(3));")]
477 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_add_signed(-2), None);")]
478 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add_signed(3), None);")]
480 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
481 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
482 #[must_use = "this returns the result of the operation, \
483 without modifying the original"]
485 pub const fn checked_add_signed(self, rhs: $SignedT) -> Option<Self> {
486 let (a, b) = self.overflowing_add_signed(rhs);
487 if unlikely!(b) {None} else {Some(a)}
490 /// Checked integer subtraction. Computes `self - rhs`, returning
491 /// `None` if overflow occurred.
498 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));")]
499 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);")]
501 #[stable(feature = "rust1", since = "1.0.0")]
502 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
503 #[must_use = "this returns the result of the operation, \
504 without modifying the original"]
506 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
507 let (a, b) = self.overflowing_sub(rhs);
508 if unlikely!(b) {None} else {Some(a)}
511 /// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
516 /// This results in undefined behavior when
517 #[doc = concat!("`self - rhs > ", stringify!($SelfT), "::MAX` or `self - rhs < ", stringify!($SelfT), "::MIN`,")]
518 /// i.e. when [`checked_sub`] would return `None`.
520 #[doc = concat!("[`checked_sub`]: ", stringify!($SelfT), "::checked_sub")]
522 feature = "unchecked_math",
523 reason = "niche optimization path",
526 #[must_use = "this returns the result of the operation, \
527 without modifying the original"]
528 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
530 pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
531 // SAFETY: the caller must uphold the safety contract for
533 unsafe { intrinsics::unchecked_sub(self, rhs) }
536 /// Checked integer multiplication. Computes `self * rhs`, returning
537 /// `None` if overflow occurred.
544 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));")]
545 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);")]
547 #[stable(feature = "rust1", since = "1.0.0")]
548 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
549 #[must_use = "this returns the result of the operation, \
550 without modifying the original"]
552 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
553 let (a, b) = self.overflowing_mul(rhs);
554 if unlikely!(b) {None} else {Some(a)}
557 /// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
562 /// This results in undefined behavior when
563 #[doc = concat!("`self * rhs > ", stringify!($SelfT), "::MAX` or `self * rhs < ", stringify!($SelfT), "::MIN`,")]
564 /// i.e. when [`checked_mul`] would return `None`.
566 #[doc = concat!("[`checked_mul`]: ", stringify!($SelfT), "::checked_mul")]
568 feature = "unchecked_math",
569 reason = "niche optimization path",
572 #[must_use = "this returns the result of the operation, \
573 without modifying the original"]
574 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
576 pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
577 // SAFETY: the caller must uphold the safety contract for
579 unsafe { intrinsics::unchecked_mul(self, rhs) }
582 /// Checked integer division. Computes `self / rhs`, returning `None`
590 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));")]
591 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);")]
593 #[stable(feature = "rust1", since = "1.0.0")]
594 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.52.0")]
595 #[must_use = "this returns the result of the operation, \
596 without modifying the original"]
598 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
599 if unlikely!(rhs == 0) {
602 // SAFETY: div by zero has been checked above and unsigned types have no other
603 // failure modes for division
604 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
608 /// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
616 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));")]
617 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);")]
619 #[stable(feature = "euclidean_division", since = "1.38.0")]
620 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
621 #[must_use = "this returns the result of the operation, \
622 without modifying the original"]
624 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
625 if unlikely!(rhs == 0) {
628 Some(self.div_euclid(rhs))
633 /// Checked integer remainder. Computes `self % rhs`, returning `None`
641 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));")]
642 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);")]
644 #[stable(feature = "wrapping", since = "1.7.0")]
645 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.52.0")]
646 #[must_use = "this returns the result of the operation, \
647 without modifying the original"]
649 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
650 if unlikely!(rhs == 0) {
653 // SAFETY: div by zero has been checked above and unsigned types have no other
654 // failure modes for division
655 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
659 /// Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
667 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));")]
668 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);")]
670 #[stable(feature = "euclidean_division", since = "1.38.0")]
671 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
672 #[must_use = "this returns the result of the operation, \
673 without modifying the original"]
675 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
676 if unlikely!(rhs == 0) {
679 Some(self.rem_euclid(rhs))
683 /// Returns the logarithm of the number with respect to an arbitrary base,
686 /// This method might not be optimized owing to implementation details;
687 /// `log2` can produce results more efficiently for base 2, and `log10`
688 /// can produce results more efficiently for base 10.
692 /// When the number is negative, zero, or if the base is not at least 2;
693 /// it panics in debug mode and the return value is 0 in release mode.
698 /// #![feature(int_log)]
699 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".log(5), 1);")]
701 #[unstable(feature = "int_log", issue = "70887")]
702 #[must_use = "this returns the result of the operation, \
703 without modifying the original"]
706 #[rustc_inherit_overflow_checks]
707 #[allow(arithmetic_overflow)]
708 pub const fn log(self, base: Self) -> u32 {
709 match self.checked_log(base) {
712 // In debug builds, trigger a panic on None.
713 // This should optimize completely out in release builds.
714 let _ = Self::MAX + 1;
721 /// Returns the base 2 logarithm of the number, rounded down.
725 /// When the number is negative or zero it panics in debug mode and
726 /// the return value is 0 in release mode.
731 /// #![feature(int_log)]
732 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".log2(), 1);")]
734 #[unstable(feature = "int_log", issue = "70887")]
735 #[must_use = "this returns the result of the operation, \
736 without modifying the original"]
739 #[rustc_inherit_overflow_checks]
740 #[allow(arithmetic_overflow)]
741 pub const fn log2(self) -> u32 {
742 match self.checked_log2() {
745 // In debug builds, trigger a panic on None.
746 // This should optimize completely out in release builds.
747 let _ = Self::MAX + 1;
754 /// Returns the base 10 logarithm of the number, rounded down.
758 /// When the number is negative or zero it panics in debug mode and the
759 /// return value is 0 in release mode.
764 /// #![feature(int_log)]
765 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".log10(), 1);")]
767 #[unstable(feature = "int_log", issue = "70887")]
768 #[must_use = "this returns the result of the operation, \
769 without modifying the original"]
772 #[rustc_inherit_overflow_checks]
773 #[allow(arithmetic_overflow)]
774 pub const fn log10(self) -> u32 {
775 match self.checked_log10() {
778 // In debug builds, trigger a panic on None.
779 // This should optimize completely out in release builds.
780 let _ = Self::MAX + 1;
787 /// Returns the logarithm of the number with respect to an arbitrary base,
790 /// Returns `None` if the number is zero, or if the base is not at least 2.
792 /// This method might not be optimized owing to implementation details;
793 /// `checked_log2` can produce results more efficiently for base 2, and
794 /// `checked_log10` can produce results more efficiently for base 10.
799 /// #![feature(int_log)]
800 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_log(5), Some(1));")]
802 #[unstable(feature = "int_log", issue = "70887")]
803 #[must_use = "this returns the result of the operation, \
804 without modifying the original"]
806 pub const fn checked_log(self, base: Self) -> Option<u32> {
807 if self <= 0 || base <= 1 {
813 // Optimization for 128 bit wide integers.
814 if Self::BITS == 128 {
815 let b = Self::log2(self) / (Self::log2(base) + 1);
817 r /= base.pow(b as u32);
828 /// Returns the base 2 logarithm of the number, rounded down.
830 /// Returns `None` if the number is zero.
835 /// #![feature(int_log)]
836 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_log2(), Some(1));")]
838 #[unstable(feature = "int_log", issue = "70887")]
839 #[must_use = "this returns the result of the operation, \
840 without modifying the original"]
842 pub const fn checked_log2(self) -> Option<u32> {
843 if let Some(x) = <$NonZeroT>::new(self) {
850 /// Returns the base 10 logarithm of the number, rounded down.
852 /// Returns `None` if the number is zero.
857 /// #![feature(int_log)]
858 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_log10(), Some(1));")]
860 #[unstable(feature = "int_log", issue = "70887")]
861 #[must_use = "this returns the result of the operation, \
862 without modifying the original"]
864 pub const fn checked_log10(self) -> Option<u32> {
865 if let Some(x) = <$NonZeroT>::new(self) {
872 /// Checked negation. Computes `-self`, returning `None` unless `self ==
875 /// Note that negating any positive integer will overflow.
882 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));")]
883 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);")]
885 #[stable(feature = "wrapping", since = "1.7.0")]
886 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
887 #[must_use = "this returns the result of the operation, \
888 without modifying the original"]
890 pub const fn checked_neg(self) -> Option<Self> {
891 let (a, b) = self.overflowing_neg();
892 if unlikely!(b) {None} else {Some(a)}
895 /// Checked shift left. Computes `self << rhs`, returning `None`
896 /// if `rhs` is larger than or equal to the number of bits in `self`.
903 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));")]
904 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);")]
906 #[stable(feature = "wrapping", since = "1.7.0")]
907 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
908 #[must_use = "this returns the result of the operation, \
909 without modifying the original"]
911 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
912 let (a, b) = self.overflowing_shl(rhs);
913 if unlikely!(b) {None} else {Some(a)}
916 /// Unchecked shift left. Computes `self << rhs`, assuming that
917 /// `rhs` is less than the number of bits in `self`.
921 /// This results in undefined behavior if `rhs` is larger than
922 /// or equal to the number of bits in `self`,
923 /// i.e. when [`checked_shl`] would return `None`.
925 #[doc = concat!("[`checked_shl`]: ", stringify!($SelfT), "::checked_shl")]
927 feature = "unchecked_math",
928 reason = "niche optimization path",
931 #[must_use = "this returns the result of the operation, \
932 without modifying the original"]
933 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
935 pub const unsafe fn unchecked_shl(self, rhs: Self) -> Self {
936 // SAFETY: the caller must uphold the safety contract for
938 unsafe { intrinsics::unchecked_shl(self, rhs) }
941 /// Checked shift right. Computes `self >> rhs`, returning `None`
942 /// if `rhs` is larger than or equal to the number of bits in `self`.
949 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));")]
950 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);")]
952 #[stable(feature = "wrapping", since = "1.7.0")]
953 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
954 #[must_use = "this returns the result of the operation, \
955 without modifying the original"]
957 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
958 let (a, b) = self.overflowing_shr(rhs);
959 if unlikely!(b) {None} else {Some(a)}
962 /// Unchecked shift right. Computes `self >> rhs`, assuming that
963 /// `rhs` is less than the number of bits in `self`.
967 /// This results in undefined behavior if `rhs` is larger than
968 /// or equal to the number of bits in `self`,
969 /// i.e. when [`checked_shr`] would return `None`.
971 #[doc = concat!("[`checked_shr`]: ", stringify!($SelfT), "::checked_shr")]
973 feature = "unchecked_math",
974 reason = "niche optimization path",
977 #[must_use = "this returns the result of the operation, \
978 without modifying the original"]
979 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
981 pub const unsafe fn unchecked_shr(self, rhs: Self) -> Self {
982 // SAFETY: the caller must uphold the safety contract for
984 unsafe { intrinsics::unchecked_shr(self, rhs) }
987 /// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
988 /// overflow occurred.
995 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));")]
996 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);")]
998 #[stable(feature = "no_panic_pow", since = "1.34.0")]
999 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1000 #[must_use = "this returns the result of the operation, \
1001 without modifying the original"]
1003 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
1007 let mut base = self;
1008 let mut acc: Self = 1;
1012 acc = try_opt!(acc.checked_mul(base));
1015 base = try_opt!(base.checked_mul(base));
1018 // since exp!=0, finally the exp must be 1.
1019 // Deal with the final bit of the exponent separately, since
1020 // squaring the base afterwards is not necessary and may cause a
1021 // needless overflow.
1023 Some(try_opt!(acc.checked_mul(base)))
1026 /// Saturating integer addition. Computes `self + rhs`, saturating at
1027 /// the numeric bounds instead of overflowing.
1034 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);")]
1035 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(127), ", stringify!($SelfT), "::MAX);")]
1037 #[stable(feature = "rust1", since = "1.0.0")]
1038 #[must_use = "this returns the result of the operation, \
1039 without modifying the original"]
1040 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1042 pub const fn saturating_add(self, rhs: Self) -> Self {
1043 intrinsics::saturating_add(self, rhs)
1046 /// Saturating addition with a signed integer. Computes `self + rhs`,
1047 /// saturating at the numeric bounds instead of overflowing.
1054 /// # #![feature(mixed_integer_ops)]
1055 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_signed(2), 3);")]
1056 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_signed(-2), 0);")]
1057 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).saturating_add_signed(4), ", stringify!($SelfT), "::MAX);")]
1059 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1060 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1061 #[must_use = "this returns the result of the operation, \
1062 without modifying the original"]
1064 pub const fn saturating_add_signed(self, rhs: $SignedT) -> Self {
1065 let (res, overflow) = self.overflowing_add(rhs as Self);
1066 if overflow == (rhs < 0) {
1068 } else if overflow {
1075 /// Saturating integer subtraction. Computes `self - rhs`, saturating
1076 /// at the numeric bounds instead of overflowing.
1083 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);")]
1084 #[doc = concat!("assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);")]
1086 #[stable(feature = "rust1", since = "1.0.0")]
1087 #[must_use = "this returns the result of the operation, \
1088 without modifying the original"]
1089 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1091 pub const fn saturating_sub(self, rhs: Self) -> Self {
1092 intrinsics::saturating_sub(self, rhs)
1095 /// Saturating integer multiplication. Computes `self * rhs`,
1096 /// saturating at the numeric bounds instead of overflowing.
1103 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);")]
1104 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),"::MAX);")]
1106 #[stable(feature = "wrapping", since = "1.7.0")]
1107 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1108 #[must_use = "this returns the result of the operation, \
1109 without modifying the original"]
1111 pub const fn saturating_mul(self, rhs: Self) -> Self {
1112 match self.checked_mul(rhs) {
1118 /// Saturating integer division. Computes `self / rhs`, saturating at the
1119 /// numeric bounds instead of overflowing.
1126 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".saturating_div(2), 2);")]
1131 #[doc = concat!("let _ = 1", stringify!($SelfT), ".saturating_div(0);")]
1134 #[stable(feature = "saturating_div", since = "1.58.0")]
1135 #[must_use = "this returns the result of the operation, \
1136 without modifying the original"]
1138 pub const fn saturating_div(self, rhs: Self) -> Self {
1139 // on unsigned types, there is no overflow in integer division
1140 self.wrapping_div(rhs)
1143 /// Saturating integer exponentiation. Computes `self.pow(exp)`,
1144 /// saturating at the numeric bounds instead of overflowing.
1151 #[doc = concat!("assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);")]
1152 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);")]
1154 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1155 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1156 #[must_use = "this returns the result of the operation, \
1157 without modifying the original"]
1159 pub const fn saturating_pow(self, exp: u32) -> Self {
1160 match self.checked_pow(exp) {
1166 /// Wrapping (modular) addition. Computes `self + rhs`,
1167 /// wrapping around at the boundary of the type.
1174 #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);")]
1175 #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);")]
1177 #[stable(feature = "rust1", since = "1.0.0")]
1178 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1179 #[must_use = "this returns the result of the operation, \
1180 without modifying the original"]
1182 pub const fn wrapping_add(self, rhs: Self) -> Self {
1183 intrinsics::wrapping_add(self, rhs)
1186 /// Wrapping (modular) addition with a signed integer. Computes
1187 /// `self + rhs`, wrapping around at the boundary of the type.
1194 /// # #![feature(mixed_integer_ops)]
1195 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_add_signed(2), 3);")]
1196 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_add_signed(-2), ", stringify!($SelfT), "::MAX);")]
1197 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).wrapping_add_signed(4), 1);")]
1199 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1200 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1201 #[must_use = "this returns the result of the operation, \
1202 without modifying the original"]
1204 pub const fn wrapping_add_signed(self, rhs: $SignedT) -> Self {
1205 self.wrapping_add(rhs as Self)
1208 /// Wrapping (modular) subtraction. Computes `self - rhs`,
1209 /// wrapping around at the boundary of the type.
1216 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);")]
1217 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::MAX), 101);")]
1219 #[stable(feature = "rust1", since = "1.0.0")]
1220 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1221 #[must_use = "this returns the result of the operation, \
1222 without modifying the original"]
1224 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1225 intrinsics::wrapping_sub(self, rhs)
1228 /// Wrapping (modular) multiplication. Computes `self *
1229 /// rhs`, wrapping around at the boundary of the type.
1235 /// Please note that this example is shared between integer types.
1236 /// Which explains why `u8` is used here.
1239 /// assert_eq!(10u8.wrapping_mul(12), 120);
1240 /// assert_eq!(25u8.wrapping_mul(12), 44);
1242 #[stable(feature = "rust1", since = "1.0.0")]
1243 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1244 #[must_use = "this returns the result of the operation, \
1245 without modifying the original"]
1247 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1248 intrinsics::wrapping_mul(self, rhs)
1251 /// Wrapping (modular) division. Computes `self / rhs`.
1252 /// Wrapped division on unsigned types is just normal division.
1253 /// There's no way wrapping could ever happen.
1254 /// This function exists, so that all operations
1255 /// are accounted for in the wrapping operations.
1262 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);")]
1264 #[stable(feature = "num_wrapping", since = "1.2.0")]
1265 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1266 #[must_use = "this returns the result of the operation, \
1267 without modifying the original"]
1269 pub const fn wrapping_div(self, rhs: Self) -> Self {
1273 /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
1274 /// Wrapped division on unsigned types is just normal division.
1275 /// There's no way wrapping could ever happen.
1276 /// This function exists, so that all operations
1277 /// are accounted for in the wrapping operations.
1278 /// Since, for the positive integers, all common
1279 /// definitions of division are equal, this
1280 /// is exactly equal to `self.wrapping_div(rhs)`.
1287 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);")]
1289 #[stable(feature = "euclidean_division", since = "1.38.0")]
1290 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1291 #[must_use = "this returns the result of the operation, \
1292 without modifying the original"]
1294 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
1298 /// Wrapping (modular) remainder. Computes `self % rhs`.
1299 /// Wrapped remainder calculation on unsigned types is
1300 /// just the regular remainder calculation.
1301 /// There's no way wrapping could ever happen.
1302 /// This function exists, so that all operations
1303 /// are accounted for in the wrapping operations.
1310 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);")]
1312 #[stable(feature = "num_wrapping", since = "1.2.0")]
1313 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1314 #[must_use = "this returns the result of the operation, \
1315 without modifying the original"]
1317 pub const fn wrapping_rem(self, rhs: Self) -> Self {
1321 /// Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
1322 /// Wrapped modulo calculation on unsigned types is
1323 /// just the regular remainder calculation.
1324 /// There's no way wrapping could ever happen.
1325 /// This function exists, so that all operations
1326 /// are accounted for in the wrapping operations.
1327 /// Since, for the positive integers, all common
1328 /// definitions of division are equal, this
1329 /// is exactly equal to `self.wrapping_rem(rhs)`.
1336 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);")]
1338 #[stable(feature = "euclidean_division", since = "1.38.0")]
1339 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1340 #[must_use = "this returns the result of the operation, \
1341 without modifying the original"]
1343 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1347 /// Wrapping (modular) negation. Computes `-self`,
1348 /// wrapping around at the boundary of the type.
1350 /// Since unsigned types do not have negative equivalents
1351 /// all applications of this function will wrap (except for `-0`).
1352 /// For values smaller than the corresponding signed type's maximum
1353 /// the result is the same as casting the corresponding signed value.
1354 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
1355 /// `MAX` is the corresponding signed type's maximum.
1361 /// Please note that this example is shared between integer types.
1362 /// Which explains why `i8` is used here.
1365 /// assert_eq!(100i8.wrapping_neg(), -100);
1366 /// assert_eq!((-128i8).wrapping_neg(), -128);
1368 #[stable(feature = "num_wrapping", since = "1.2.0")]
1369 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1370 #[must_use = "this returns the result of the operation, \
1371 without modifying the original"]
1373 pub const fn wrapping_neg(self) -> Self {
1374 (0 as $SelfT).wrapping_sub(self)
1377 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1378 /// where `mask` removes any high-order bits of `rhs` that
1379 /// would cause the shift to exceed the bitwidth of the type.
1381 /// Note that this is *not* the same as a rotate-left; the
1382 /// RHS of a wrapping shift-left is restricted to the range
1383 /// of the type, rather than the bits shifted out of the LHS
1384 /// being returned to the other end. The primitive integer
1385 /// types all implement a [`rotate_left`](Self::rotate_left) function,
1386 /// which may be what you want instead.
1393 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);")]
1394 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);")]
1396 #[stable(feature = "num_wrapping", since = "1.2.0")]
1397 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1398 #[must_use = "this returns the result of the operation, \
1399 without modifying the original"]
1401 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1402 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1405 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1409 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
1410 /// where `mask` removes any high-order bits of `rhs` that
1411 /// would cause the shift to exceed the bitwidth of the type.
1413 /// Note that this is *not* the same as a rotate-right; the
1414 /// RHS of a wrapping shift-right is restricted to the range
1415 /// of the type, rather than the bits shifted out of the LHS
1416 /// being returned to the other end. The primitive integer
1417 /// types all implement a [`rotate_right`](Self::rotate_right) function,
1418 /// which may be what you want instead.
1425 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);")]
1426 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);")]
1428 #[stable(feature = "num_wrapping", since = "1.2.0")]
1429 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1430 #[must_use = "this returns the result of the operation, \
1431 without modifying the original"]
1433 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1434 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1437 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1441 /// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1442 /// wrapping around at the boundary of the type.
1449 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);")]
1450 /// assert_eq!(3u8.wrapping_pow(6), 217);
1452 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1453 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1454 #[must_use = "this returns the result of the operation, \
1455 without modifying the original"]
1457 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
1461 let mut base = self;
1462 let mut acc: Self = 1;
1466 acc = acc.wrapping_mul(base);
1469 base = base.wrapping_mul(base);
1472 // since exp!=0, finally the exp must be 1.
1473 // Deal with the final bit of the exponent separately, since
1474 // squaring the base afterwards is not necessary and may cause a
1475 // needless overflow.
1476 acc.wrapping_mul(base)
1479 /// Calculates `self` + `rhs`
1481 /// Returns a tuple of the addition along with a boolean indicating
1482 /// whether an arithmetic overflow would occur. If an overflow would
1483 /// have occurred then the wrapped value is returned.
1491 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));")]
1492 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));")]
1494 #[stable(feature = "wrapping", since = "1.7.0")]
1495 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1496 #[must_use = "this returns the result of the operation, \
1497 without modifying the original"]
1499 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1500 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1504 /// Calculates `self + rhs + carry` without the ability to overflow.
1506 /// Performs "ternary addition" which takes in an extra bit to add, and may return an
1507 /// additional bit of overflow. This allows for chaining together multiple additions
1508 /// to create "big integers" which represent larger values.
1510 #[doc = concat!("This can be thought of as a ", stringify!($BITS), "-bit \"full adder\", in the electronics sense.")]
1517 /// #![feature(bigint_helper_methods)]
1518 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".carrying_add(2, false), (7, false));")]
1519 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".carrying_add(2, true), (8, false));")]
1520 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.carrying_add(1, false), (0, true));")]
1521 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.carrying_add(0, true), (0, true));")]
1522 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.carrying_add(1, true), (1, true));")]
1523 #[doc = concat!("assert_eq!(",
1524 stringify!($SelfT), "::MAX.carrying_add(", stringify!($SelfT), "::MAX, true), ",
1525 "(", stringify!($SelfT), "::MAX, true));"
1529 /// If `carry` is false, this method is equivalent to [`overflowing_add`](Self::overflowing_add):
1532 /// #![feature(bigint_helper_methods)]
1533 #[doc = concat!("assert_eq!(5_", stringify!($SelfT), ".carrying_add(2, false), 5_", stringify!($SelfT), ".overflowing_add(2));")]
1534 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.carrying_add(1, false), ", stringify!($SelfT), "::MAX.overflowing_add(1));")]
1536 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
1537 #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")]
1538 #[must_use = "this returns the result of the operation, \
1539 without modifying the original"]
1541 pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
1542 // note: longer-term this should be done via an intrinsic, but this has been shown
1543 // to generate optimal code for now, and LLVM doesn't have an equivalent intrinsic
1544 let (a, b) = self.overflowing_add(rhs);
1545 let (c, d) = a.overflowing_add(carry as $SelfT);
1549 /// Calculates `self` + `rhs` with a signed `rhs`
1551 /// Returns a tuple of the addition along with a boolean indicating
1552 /// whether an arithmetic overflow would occur. If an overflow would
1553 /// have occurred then the wrapped value is returned.
1560 /// # #![feature(mixed_integer_ops)]
1561 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_signed(2), (3, false));")]
1562 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_signed(-2), (", stringify!($SelfT), "::MAX, true));")]
1563 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).overflowing_add_signed(4), (1, true));")]
1565 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1566 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1567 #[must_use = "this returns the result of the operation, \
1568 without modifying the original"]
1570 pub const fn overflowing_add_signed(self, rhs: $SignedT) -> (Self, bool) {
1571 let (res, overflowed) = self.overflowing_add(rhs as Self);
1572 (res, overflowed ^ (rhs < 0))
1575 /// Calculates `self` - `rhs`
1577 /// Returns a tuple of the subtraction along with a boolean indicating
1578 /// whether an arithmetic overflow would occur. If an overflow would
1579 /// have occurred then the wrapped value is returned.
1587 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));")]
1588 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")]
1590 #[stable(feature = "wrapping", since = "1.7.0")]
1591 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1592 #[must_use = "this returns the result of the operation, \
1593 without modifying the original"]
1595 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1596 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1600 /// Calculates `self - rhs - borrow` without the ability to overflow.
1602 /// Performs "ternary subtraction" which takes in an extra bit to subtract, and may return
1603 /// an additional bit of overflow. This allows for chaining together multiple subtractions
1604 /// to create "big integers" which represent larger values.
1611 /// #![feature(bigint_helper_methods)]
1612 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".borrowing_sub(2, false), (3, false));")]
1613 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".borrowing_sub(2, true), (2, false));")]
1614 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".borrowing_sub(1, false), (", stringify!($SelfT), "::MAX, true));")]
1615 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".borrowing_sub(1, true), (", stringify!($SelfT), "::MAX - 1, true));")]
1617 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
1618 #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")]
1619 #[must_use = "this returns the result of the operation, \
1620 without modifying the original"]
1622 pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
1623 // note: longer-term this should be done via an intrinsic, but this has been shown
1624 // to generate optimal code for now, and LLVM doesn't have an equivalent intrinsic
1625 let (a, b) = self.overflowing_sub(rhs);
1626 let (c, d) = a.overflowing_sub(borrow as $SelfT);
1630 /// Computes the absolute difference between `self` and `other`.
1637 /// #![feature(int_abs_diff)]
1638 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(80), 20", stringify!($SelfT), ");")]
1639 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(110), 10", stringify!($SelfT), ");")]
1641 #[unstable(feature = "int_abs_diff", issue = "89492")]
1642 #[must_use = "this returns the result of the operation, \
1643 without modifying the original"]
1645 pub const fn abs_diff(self, other: Self) -> Self {
1646 if mem::size_of::<Self>() == 1 {
1647 // Trick LLVM into generating the psadbw instruction when SSE2
1648 // is available and this function is autovectorized for u8's.
1649 (self as i32).wrapping_sub(other as i32).abs() as Self
1659 /// Calculates the multiplication of `self` and `rhs`.
1661 /// Returns a tuple of the multiplication along with a boolean
1662 /// indicating whether an arithmetic overflow would occur. If an
1663 /// overflow would have occurred then the wrapped value is returned.
1669 /// Please note that this example is shared between integer types.
1670 /// Which explains why `u32` is used here.
1673 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
1674 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
1676 #[stable(feature = "wrapping", since = "1.7.0")]
1677 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1678 #[must_use = "this returns the result of the operation, \
1679 without modifying the original"]
1681 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1682 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1686 /// Calculates the divisor when `self` is divided by `rhs`.
1688 /// Returns a tuple of the divisor along with a boolean indicating
1689 /// whether an arithmetic overflow would occur. Note that for unsigned
1690 /// integers overflow never occurs, so the second value is always
1695 /// This function will panic if `rhs` is 0.
1702 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));")]
1705 #[stable(feature = "wrapping", since = "1.7.0")]
1706 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1707 #[must_use = "this returns the result of the operation, \
1708 without modifying the original"]
1709 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1713 /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1715 /// Returns a tuple of the divisor along with a boolean indicating
1716 /// whether an arithmetic overflow would occur. Note that for unsigned
1717 /// integers overflow never occurs, so the second value is always
1719 /// Since, for the positive integers, all common
1720 /// definitions of division are equal, this
1721 /// is exactly equal to `self.overflowing_div(rhs)`.
1725 /// This function will panic if `rhs` is 0.
1732 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));")]
1735 #[stable(feature = "euclidean_division", since = "1.38.0")]
1736 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1737 #[must_use = "this returns the result of the operation, \
1738 without modifying the original"]
1739 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1743 /// Calculates the remainder when `self` is divided by `rhs`.
1745 /// Returns a tuple of the remainder after dividing along with a boolean
1746 /// indicating whether an arithmetic overflow would occur. Note that for
1747 /// unsigned integers overflow never occurs, so the second value is
1752 /// This function will panic if `rhs` is 0.
1759 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));")]
1762 #[stable(feature = "wrapping", since = "1.7.0")]
1763 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1764 #[must_use = "this returns the result of the operation, \
1765 without modifying the original"]
1766 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1770 /// Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
1772 /// Returns a tuple of the modulo after dividing along with a boolean
1773 /// indicating whether an arithmetic overflow would occur. Note that for
1774 /// unsigned integers overflow never occurs, so the second value is
1776 /// Since, for the positive integers, all common
1777 /// definitions of division are equal, this operation
1778 /// is exactly equal to `self.overflowing_rem(rhs)`.
1782 /// This function will panic if `rhs` is 0.
1789 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));")]
1792 #[stable(feature = "euclidean_division", since = "1.38.0")]
1793 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1794 #[must_use = "this returns the result of the operation, \
1795 without modifying the original"]
1796 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1800 /// Negates self in an overflowing fashion.
1802 /// Returns `!self + 1` using wrapping operations to return the value
1803 /// that represents the negation of this unsigned value. Note that for
1804 /// positive unsigned values overflow always occurs, but negating 0 does
1812 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));")]
1813 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT), ", true));")]
1816 #[stable(feature = "wrapping", since = "1.7.0")]
1817 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1818 #[must_use = "this returns the result of the operation, \
1819 without modifying the original"]
1820 pub const fn overflowing_neg(self) -> (Self, bool) {
1821 ((!self).wrapping_add(1), self != 0)
1824 /// Shifts self left by `rhs` bits.
1826 /// Returns a tuple of the shifted version of self along with a boolean
1827 /// indicating whether the shift value was larger than or equal to the
1828 /// number of bits. If the shift value is too large, then value is
1829 /// masked (N-1) where N is the number of bits, and this value is then
1830 /// used to perform the shift.
1837 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));")]
1838 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));")]
1840 #[stable(feature = "wrapping", since = "1.7.0")]
1841 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1842 #[must_use = "this returns the result of the operation, \
1843 without modifying the original"]
1845 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1846 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1849 /// Shifts self right by `rhs` bits.
1851 /// Returns a tuple of the shifted version of self along with a boolean
1852 /// indicating whether the shift value was larger than or equal to the
1853 /// number of bits. If the shift value is too large, then value is
1854 /// masked (N-1) where N is the number of bits, and this value is then
1855 /// used to perform the shift.
1862 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));")]
1863 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));")]
1865 #[stable(feature = "wrapping", since = "1.7.0")]
1866 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1867 #[must_use = "this returns the result of the operation, \
1868 without modifying the original"]
1870 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1871 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1874 /// Raises self to the power of `exp`, using exponentiation by squaring.
1876 /// Returns a tuple of the exponentiation along with a bool indicating
1877 /// whether an overflow happened.
1884 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));")]
1885 /// assert_eq!(3u8.overflowing_pow(6), (217, true));
1887 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1888 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1889 #[must_use = "this returns the result of the operation, \
1890 without modifying the original"]
1892 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1896 let mut base = self;
1897 let mut acc: Self = 1;
1898 let mut overflown = false;
1899 // Scratch space for storing results of overflowing_mul.
1904 r = acc.overflowing_mul(base);
1909 r = base.overflowing_mul(base);
1914 // since exp!=0, finally the exp must be 1.
1915 // Deal with the final bit of the exponent separately, since
1916 // squaring the base afterwards is not necessary and may cause a
1917 // needless overflow.
1918 r = acc.overflowing_mul(base);
1924 /// Raises self to the power of `exp`, using exponentiation by squaring.
1931 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".pow(5), 32);")]
1933 #[stable(feature = "rust1", since = "1.0.0")]
1934 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1935 #[must_use = "this returns the result of the operation, \
1936 without modifying the original"]
1938 #[rustc_inherit_overflow_checks]
1939 pub const fn pow(self, mut exp: u32) -> Self {
1943 let mut base = self;
1954 // since exp!=0, finally the exp must be 1.
1955 // Deal with the final bit of the exponent separately, since
1956 // squaring the base afterwards is not necessary and may cause a
1957 // needless overflow.
1961 /// Performs Euclidean division.
1963 /// Since, for the positive integers, all common
1964 /// definitions of division are equal, this
1965 /// is exactly equal to `self / rhs`.
1969 /// This function will panic if `rhs` is 0.
1976 #[doc = concat!("assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type")]
1978 #[stable(feature = "euclidean_division", since = "1.38.0")]
1979 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1980 #[must_use = "this returns the result of the operation, \
1981 without modifying the original"]
1983 #[rustc_inherit_overflow_checks]
1984 pub const fn div_euclid(self, rhs: Self) -> Self {
1989 /// Calculates the least remainder of `self (mod rhs)`.
1991 /// Since, for the positive integers, all common
1992 /// definitions of division are equal, this
1993 /// is exactly equal to `self % rhs`.
1997 /// This function will panic if `rhs` is 0.
2004 #[doc = concat!("assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type")]
2006 #[stable(feature = "euclidean_division", since = "1.38.0")]
2007 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
2008 #[must_use = "this returns the result of the operation, \
2009 without modifying the original"]
2011 #[rustc_inherit_overflow_checks]
2012 pub const fn rem_euclid(self, rhs: Self) -> Self {
2016 /// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
2018 /// This is the same as performing `self / rhs` for all unsigned integers.
2022 /// This function will panic if `rhs` is 0.
2029 /// #![feature(int_roundings)]
2030 #[doc = concat!("assert_eq!(7_", stringify!($SelfT), ".div_floor(4), 1);")]
2032 #[unstable(feature = "int_roundings", issue = "88581")]
2033 #[must_use = "this returns the result of the operation, \
2034 without modifying the original"]
2036 #[rustc_inherit_overflow_checks]
2037 pub const fn div_floor(self, rhs: Self) -> Self {
2041 /// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
2045 /// This function will panic if `rhs` is 0.
2052 /// #![feature(int_roundings)]
2053 #[doc = concat!("assert_eq!(7_", stringify!($SelfT), ".div_ceil(4), 2);")]
2055 #[unstable(feature = "int_roundings", issue = "88581")]
2056 #[must_use = "this returns the result of the operation, \
2057 without modifying the original"]
2059 #[rustc_inherit_overflow_checks]
2060 pub const fn div_ceil(self, rhs: Self) -> Self {
2063 if r > 0 && rhs > 0 {
2070 /// Calculates the smallest value greater than or equal to `self` that
2071 /// is a multiple of `rhs`.
2075 /// This function will panic if `rhs` is 0 or the operation results in overflow.
2082 /// #![feature(int_roundings)]
2083 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".next_multiple_of(8), 16);")]
2084 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".next_multiple_of(8), 24);")]
2086 #[unstable(feature = "int_roundings", issue = "88581")]
2087 #[must_use = "this returns the result of the operation, \
2088 without modifying the original"]
2090 #[rustc_inherit_overflow_checks]
2091 pub const fn next_multiple_of(self, rhs: Self) -> Self {
2094 r => self + (rhs - r)
2098 /// Calculates the smallest value greater than or equal to `self` that
2099 /// is a multiple of `rhs`. Returns `None` is `rhs` is zero or the
2100 /// operation would result in overflow.
2107 /// #![feature(int_roundings)]
2108 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(16));")]
2109 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(24));")]
2110 #[doc = concat!("assert_eq!(1_", stringify!($SelfT), ".checked_next_multiple_of(0), None);")]
2111 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_multiple_of(2), None);")]
2113 #[unstable(feature = "int_roundings", issue = "88581")]
2114 #[must_use = "this returns the result of the operation, \
2115 without modifying the original"]
2117 #[rustc_inherit_overflow_checks]
2118 pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
2119 match try_opt!(self.checked_rem(rhs)) {
2121 r => self.checked_add(try_opt!(rhs.checked_sub(r)))
2125 /// Returns `true` if and only if `self == 2^k` for some `k`.
2132 #[doc = concat!("assert!(16", stringify!($SelfT), ".is_power_of_two());")]
2133 #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_power_of_two());")]
2136 #[stable(feature = "rust1", since = "1.0.0")]
2137 #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
2139 pub const fn is_power_of_two(self) -> bool {
2140 self.count_ones() == 1
2143 // Returns one less than next power of two.
2144 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
2146 // 8u8.one_less_than_next_power_of_two() == 7
2147 // 6u8.one_less_than_next_power_of_two() == 7
2149 // This method cannot overflow, as in the `next_power_of_two`
2150 // overflow cases it instead ends up returning the maximum value
2151 // of the type, and can return 0 for 0.
2153 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2154 const fn one_less_than_next_power_of_two(self) -> Self {
2155 if self <= 1 { return 0; }
2158 // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros.
2159 // That means the shift is always in-bounds, and some processors
2160 // (such as intel pre-haswell) have more efficient ctlz
2161 // intrinsics when the argument is non-zero.
2162 let z = unsafe { intrinsics::ctlz_nonzero(p) };
2166 /// Returns the smallest power of two greater than or equal to `self`.
2168 /// When return value overflows (i.e., `self > (1 << (N-1))` for type
2169 /// `uN`), it panics in debug mode and the return value is wrapped to 0 in
2170 /// release mode (the only situation in which method can return 0).
2177 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);")]
2178 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);")]
2180 #[stable(feature = "rust1", since = "1.0.0")]
2181 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2182 #[must_use = "this returns the result of the operation, \
2183 without modifying the original"]
2185 #[rustc_inherit_overflow_checks]
2186 pub const fn next_power_of_two(self) -> Self {
2187 self.one_less_than_next_power_of_two() + 1
2190 /// Returns the smallest power of two greater than or equal to `n`. If
2191 /// the next power of two is greater than the type's maximum value,
2192 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
2199 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_next_power_of_two(), Some(2));")]
2200 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));")]
2201 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_power_of_two(), None);")]
2204 #[stable(feature = "rust1", since = "1.0.0")]
2205 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2206 #[must_use = "this returns the result of the operation, \
2207 without modifying the original"]
2208 pub const fn checked_next_power_of_two(self) -> Option<Self> {
2209 self.one_less_than_next_power_of_two().checked_add(1)
2212 /// Returns the smallest power of two greater than or equal to `n`. If
2213 /// the next power of two is greater than the type's maximum value,
2214 /// the return value is wrapped to `0`.
2221 /// #![feature(wrapping_next_power_of_two)]
2223 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);")]
2224 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);")]
2225 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_next_power_of_two(), 0);")]
2227 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
2228 reason = "needs decision on wrapping behaviour")]
2229 #[rustc_const_unstable(feature = "wrapping_next_power_of_two", issue = "32463")]
2230 #[must_use = "this returns the result of the operation, \
2231 without modifying the original"]
2232 pub const fn wrapping_next_power_of_two(self) -> Self {
2233 self.one_less_than_next_power_of_two().wrapping_add(1)
2236 /// Return the memory representation of this integer as a byte array in
2237 /// big-endian (network) byte order.
2239 #[doc = $to_xe_bytes_doc]
2244 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();")]
2245 #[doc = concat!("assert_eq!(bytes, ", $be_bytes, ");")]
2247 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2248 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2249 #[must_use = "this returns the result of the operation, \
2250 without modifying the original"]
2252 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2253 self.to_be().to_ne_bytes()
2256 /// Return the memory representation of this integer as a byte array in
2257 /// little-endian byte order.
2259 #[doc = $to_xe_bytes_doc]
2264 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();")]
2265 #[doc = concat!("assert_eq!(bytes, ", $le_bytes, ");")]
2267 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2268 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2269 #[must_use = "this returns the result of the operation, \
2270 without modifying the original"]
2272 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2273 self.to_le().to_ne_bytes()
2276 /// Return the memory representation of this integer as a byte array in
2277 /// native byte order.
2279 /// As the target platform's native endianness is used, portable code
2280 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2283 #[doc = $to_xe_bytes_doc]
2285 /// [`to_be_bytes`]: Self::to_be_bytes
2286 /// [`to_le_bytes`]: Self::to_le_bytes
2291 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();")]
2294 /// if cfg!(target_endian = "big") {
2295 #[doc = concat!(" ", $be_bytes)]
2297 #[doc = concat!(" ", $le_bytes)]
2301 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2302 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2303 #[must_use = "this returns the result of the operation, \
2304 without modifying the original"]
2305 // SAFETY: const sound because integers are plain old datatypes so we can always
2306 // transmute them to arrays of bytes
2308 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2309 // SAFETY: integers are plain old datatypes so we can always transmute them to
2311 unsafe { mem::transmute(self) }
2314 /// Create a native endian integer value from its representation
2315 /// as a byte array in big endian.
2317 #[doc = $from_xe_bytes_doc]
2322 #[doc = concat!("let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");")]
2323 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2326 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2329 #[doc = concat!("fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2330 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2332 #[doc = concat!(" ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())")]
2335 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2336 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2339 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2340 Self::from_be(Self::from_ne_bytes(bytes))
2343 /// Create a native endian integer value from its representation
2344 /// as a byte array in little endian.
2346 #[doc = $from_xe_bytes_doc]
2351 #[doc = concat!("let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");")]
2352 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2355 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2358 #[doc = concat!("fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2359 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2361 #[doc = concat!(" ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())")]
2364 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2365 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2368 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2369 Self::from_le(Self::from_ne_bytes(bytes))
2372 /// Create a native endian integer value from its memory representation
2373 /// as a byte array in native endianness.
2375 /// As the target platform's native endianness is used, portable code
2376 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2377 /// appropriate instead.
2379 /// [`from_be_bytes`]: Self::from_be_bytes
2380 /// [`from_le_bytes`]: Self::from_le_bytes
2382 #[doc = $from_xe_bytes_doc]
2387 #[doc = concat!("let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {")]
2388 #[doc = concat!(" ", $be_bytes, "")]
2390 #[doc = concat!(" ", $le_bytes, "")]
2392 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2395 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2398 #[doc = concat!("fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2399 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2401 #[doc = concat!(" ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())")]
2404 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2405 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2407 // SAFETY: const sound because integers are plain old datatypes so we can always
2408 // transmute to them
2410 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2411 // SAFETY: integers are plain old datatypes so we can always transmute to them
2412 unsafe { mem::transmute(bytes) }
2415 /// New code should prefer to use
2416 #[doc = concat!("[`", stringify!($SelfT), "::MIN", "`] instead.")]
2418 /// Returns the smallest value that can be represented by this integer type.
2419 #[stable(feature = "rust1", since = "1.0.0")]
2422 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2423 #[rustc_deprecated(since = "TBD", reason = "replaced by the `MIN` associated constant on this type")]
2424 pub const fn min_value() -> Self { Self::MIN }
2426 /// New code should prefer to use
2427 #[doc = concat!("[`", stringify!($SelfT), "::MAX", "`] instead.")]
2429 /// Returns the largest value that can be represented by this integer type.
2430 #[stable(feature = "rust1", since = "1.0.0")]
2433 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2434 #[rustc_deprecated(since = "TBD", reason = "replaced by the `MAX` associated constant on this type")]
2435 pub const fn max_value() -> Self { Self::MAX }