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 = "reverse_bits", 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_div", 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_div", 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 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 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 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 #[rustc_const_stable(feature = "saturating_div", since = "1.58.0")]
1136 #[must_use = "this returns the result of the operation, \
1137 without modifying the original"]
1139 pub const fn saturating_div(self, rhs: Self) -> Self {
1140 // on unsigned types, there is no overflow in integer division
1141 self.wrapping_div(rhs)
1144 /// Saturating integer exponentiation. Computes `self.pow(exp)`,
1145 /// saturating at the numeric bounds instead of overflowing.
1152 #[doc = concat!("assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);")]
1153 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);")]
1155 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1156 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1157 #[must_use = "this returns the result of the operation, \
1158 without modifying the original"]
1160 pub const fn saturating_pow(self, exp: u32) -> Self {
1161 match self.checked_pow(exp) {
1167 /// Wrapping (modular) addition. Computes `self + rhs`,
1168 /// wrapping around at the boundary of the type.
1175 #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);")]
1176 #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);")]
1178 #[stable(feature = "rust1", since = "1.0.0")]
1179 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1180 #[must_use = "this returns the result of the operation, \
1181 without modifying the original"]
1183 pub const fn wrapping_add(self, rhs: Self) -> Self {
1184 intrinsics::wrapping_add(self, rhs)
1187 /// Wrapping (modular) addition with a signed integer. Computes
1188 /// `self + rhs`, wrapping around at the boundary of the type.
1195 /// # #![feature(mixed_integer_ops)]
1196 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_add_signed(2), 3);")]
1197 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_add_signed(-2), ", stringify!($SelfT), "::MAX);")]
1198 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).wrapping_add_signed(4), 1);")]
1200 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1201 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1202 #[must_use = "this returns the result of the operation, \
1203 without modifying the original"]
1205 pub const fn wrapping_add_signed(self, rhs: $SignedT) -> Self {
1206 self.wrapping_add(rhs as Self)
1209 /// Wrapping (modular) subtraction. Computes `self - rhs`,
1210 /// wrapping around at the boundary of the type.
1217 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);")]
1218 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::MAX), 101);")]
1220 #[stable(feature = "rust1", since = "1.0.0")]
1221 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1222 #[must_use = "this returns the result of the operation, \
1223 without modifying the original"]
1225 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1226 intrinsics::wrapping_sub(self, rhs)
1229 /// Wrapping (modular) multiplication. Computes `self *
1230 /// rhs`, wrapping around at the boundary of the type.
1236 /// Please note that this example is shared between integer types.
1237 /// Which explains why `u8` is used here.
1240 /// assert_eq!(10u8.wrapping_mul(12), 120);
1241 /// assert_eq!(25u8.wrapping_mul(12), 44);
1243 #[stable(feature = "rust1", since = "1.0.0")]
1244 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1245 #[must_use = "this returns the result of the operation, \
1246 without modifying the original"]
1248 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1249 intrinsics::wrapping_mul(self, rhs)
1252 /// Wrapping (modular) division. Computes `self / rhs`.
1253 /// Wrapped division on unsigned types is just normal division.
1254 /// There's no way wrapping could ever happen.
1255 /// This function exists, so that all operations
1256 /// are accounted for in the wrapping operations.
1263 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);")]
1265 #[stable(feature = "num_wrapping", since = "1.2.0")]
1266 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1267 #[must_use = "this returns the result of the operation, \
1268 without modifying the original"]
1270 pub const fn wrapping_div(self, rhs: Self) -> Self {
1274 /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
1275 /// Wrapped division on unsigned types is just normal division.
1276 /// There's no way wrapping could ever happen.
1277 /// This function exists, so that all operations
1278 /// are accounted for in the wrapping operations.
1279 /// Since, for the positive integers, all common
1280 /// definitions of division are equal, this
1281 /// is exactly equal to `self.wrapping_div(rhs)`.
1288 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);")]
1290 #[stable(feature = "euclidean_division", since = "1.38.0")]
1291 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1292 #[must_use = "this returns the result of the operation, \
1293 without modifying the original"]
1295 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
1299 /// Wrapping (modular) remainder. Computes `self % rhs`.
1300 /// Wrapped remainder calculation on unsigned types is
1301 /// just the regular remainder calculation.
1302 /// There's no way wrapping could ever happen.
1303 /// This function exists, so that all operations
1304 /// are accounted for in the wrapping operations.
1311 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);")]
1313 #[stable(feature = "num_wrapping", since = "1.2.0")]
1314 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1315 #[must_use = "this returns the result of the operation, \
1316 without modifying the original"]
1318 pub const fn wrapping_rem(self, rhs: Self) -> Self {
1322 /// Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
1323 /// Wrapped modulo calculation on unsigned types is
1324 /// just the regular remainder calculation.
1325 /// There's no way wrapping could ever happen.
1326 /// This function exists, so that all operations
1327 /// are accounted for in the wrapping operations.
1328 /// Since, for the positive integers, all common
1329 /// definitions of division are equal, this
1330 /// is exactly equal to `self.wrapping_rem(rhs)`.
1337 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);")]
1339 #[stable(feature = "euclidean_division", since = "1.38.0")]
1340 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1341 #[must_use = "this returns the result of the operation, \
1342 without modifying the original"]
1344 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1348 /// Wrapping (modular) negation. Computes `-self`,
1349 /// wrapping around at the boundary of the type.
1351 /// Since unsigned types do not have negative equivalents
1352 /// all applications of this function will wrap (except for `-0`).
1353 /// For values smaller than the corresponding signed type's maximum
1354 /// the result is the same as casting the corresponding signed value.
1355 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
1356 /// `MAX` is the corresponding signed type's maximum.
1362 /// Please note that this example is shared between integer types.
1363 /// Which explains why `i8` is used here.
1366 /// assert_eq!(100i8.wrapping_neg(), -100);
1367 /// assert_eq!((-128i8).wrapping_neg(), -128);
1369 #[stable(feature = "num_wrapping", since = "1.2.0")]
1370 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1371 #[must_use = "this returns the result of the operation, \
1372 without modifying the original"]
1374 pub const fn wrapping_neg(self) -> Self {
1375 (0 as $SelfT).wrapping_sub(self)
1378 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1379 /// where `mask` removes any high-order bits of `rhs` that
1380 /// would cause the shift to exceed the bitwidth of the type.
1382 /// Note that this is *not* the same as a rotate-left; the
1383 /// RHS of a wrapping shift-left is restricted to the range
1384 /// of the type, rather than the bits shifted out of the LHS
1385 /// being returned to the other end. The primitive integer
1386 /// types all implement a [`rotate_left`](Self::rotate_left) function,
1387 /// which may be what you want instead.
1394 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);")]
1395 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);")]
1397 #[stable(feature = "num_wrapping", since = "1.2.0")]
1398 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1399 #[must_use = "this returns the result of the operation, \
1400 without modifying the original"]
1402 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1403 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1406 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1410 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
1411 /// where `mask` removes any high-order bits of `rhs` that
1412 /// would cause the shift to exceed the bitwidth of the type.
1414 /// Note that this is *not* the same as a rotate-right; the
1415 /// RHS of a wrapping shift-right is restricted to the range
1416 /// of the type, rather than the bits shifted out of the LHS
1417 /// being returned to the other end. The primitive integer
1418 /// types all implement a [`rotate_right`](Self::rotate_right) function,
1419 /// which may be what you want instead.
1426 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);")]
1427 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);")]
1429 #[stable(feature = "num_wrapping", since = "1.2.0")]
1430 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1431 #[must_use = "this returns the result of the operation, \
1432 without modifying the original"]
1434 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1435 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1438 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1442 /// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1443 /// wrapping around at the boundary of the type.
1450 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);")]
1451 /// assert_eq!(3u8.wrapping_pow(6), 217);
1453 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1454 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1455 #[must_use = "this returns the result of the operation, \
1456 without modifying the original"]
1458 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
1462 let mut base = self;
1463 let mut acc: Self = 1;
1467 acc = acc.wrapping_mul(base);
1470 base = base.wrapping_mul(base);
1473 // since exp!=0, finally the exp must be 1.
1474 // Deal with the final bit of the exponent separately, since
1475 // squaring the base afterwards is not necessary and may cause a
1476 // needless overflow.
1477 acc.wrapping_mul(base)
1480 /// Calculates `self` + `rhs`
1482 /// Returns a tuple of the addition along with a boolean indicating
1483 /// whether an arithmetic overflow would occur. If an overflow would
1484 /// have occurred then the wrapped value is returned.
1492 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));")]
1493 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));")]
1495 #[stable(feature = "wrapping", since = "1.7.0")]
1496 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1497 #[must_use = "this returns the result of the operation, \
1498 without modifying the original"]
1500 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1501 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1505 /// Calculates `self + rhs + carry` without the ability to overflow.
1507 /// Performs "ternary addition" which takes in an extra bit to add, and may return an
1508 /// additional bit of overflow. This allows for chaining together multiple additions
1509 /// to create "big integers" which represent larger values.
1511 #[doc = concat!("This can be thought of as a ", stringify!($BITS), "-bit \"full adder\", in the electronics sense.")]
1518 /// #![feature(bigint_helper_methods)]
1519 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".carrying_add(2, false), (7, false));")]
1520 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".carrying_add(2, true), (8, false));")]
1521 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.carrying_add(1, false), (0, true));")]
1522 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.carrying_add(0, true), (0, true));")]
1523 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.carrying_add(1, true), (1, true));")]
1524 #[doc = concat!("assert_eq!(",
1525 stringify!($SelfT), "::MAX.carrying_add(", stringify!($SelfT), "::MAX, true), ",
1526 "(", stringify!($SelfT), "::MAX, true));"
1530 /// If `carry` is false, this method is equivalent to [`overflowing_add`](Self::overflowing_add):
1533 /// #![feature(bigint_helper_methods)]
1534 #[doc = concat!("assert_eq!(5_", stringify!($SelfT), ".carrying_add(2, false), 5_", stringify!($SelfT), ".overflowing_add(2));")]
1535 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.carrying_add(1, false), ", stringify!($SelfT), "::MAX.overflowing_add(1));")]
1537 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
1538 #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")]
1539 #[must_use = "this returns the result of the operation, \
1540 without modifying the original"]
1542 pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
1543 // note: longer-term this should be done via an intrinsic, but this has been shown
1544 // to generate optimal code for now, and LLVM doesn't have an equivalent intrinsic
1545 let (a, b) = self.overflowing_add(rhs);
1546 let (c, d) = a.overflowing_add(carry as $SelfT);
1550 /// Calculates `self` + `rhs` with a signed `rhs`
1552 /// Returns a tuple of the addition along with a boolean indicating
1553 /// whether an arithmetic overflow would occur. If an overflow would
1554 /// have occurred then the wrapped value is returned.
1561 /// # #![feature(mixed_integer_ops)]
1562 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_signed(2), (3, false));")]
1563 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_signed(-2), (", stringify!($SelfT), "::MAX, true));")]
1564 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).overflowing_add_signed(4), (1, true));")]
1566 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1567 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1568 #[must_use = "this returns the result of the operation, \
1569 without modifying the original"]
1571 pub const fn overflowing_add_signed(self, rhs: $SignedT) -> (Self, bool) {
1572 let (res, overflowed) = self.overflowing_add(rhs as Self);
1573 (res, overflowed ^ (rhs < 0))
1576 /// Calculates `self` - `rhs`
1578 /// Returns a tuple of the subtraction along with a boolean indicating
1579 /// whether an arithmetic overflow would occur. If an overflow would
1580 /// have occurred then the wrapped value is returned.
1588 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));")]
1589 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")]
1591 #[stable(feature = "wrapping", since = "1.7.0")]
1592 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1593 #[must_use = "this returns the result of the operation, \
1594 without modifying the original"]
1596 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1597 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1601 /// Calculates `self - rhs - borrow` without the ability to overflow.
1603 /// Performs "ternary subtraction" which takes in an extra bit to subtract, and may return
1604 /// an additional bit of overflow. This allows for chaining together multiple subtractions
1605 /// to create "big integers" which represent larger values.
1612 /// #![feature(bigint_helper_methods)]
1613 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".borrowing_sub(2, false), (3, false));")]
1614 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".borrowing_sub(2, true), (2, false));")]
1615 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".borrowing_sub(1, false), (", stringify!($SelfT), "::MAX, true));")]
1616 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".borrowing_sub(1, true), (", stringify!($SelfT), "::MAX - 1, true));")]
1618 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
1619 #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")]
1620 #[must_use = "this returns the result of the operation, \
1621 without modifying the original"]
1623 pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
1624 // note: longer-term this should be done via an intrinsic, but this has been shown
1625 // to generate optimal code for now, and LLVM doesn't have an equivalent intrinsic
1626 let (a, b) = self.overflowing_sub(rhs);
1627 let (c, d) = a.overflowing_sub(borrow as $SelfT);
1631 /// Computes the absolute difference between `self` and `other`.
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 #[stable(feature = "int_abs_diff", since = "1.60.0")]
1642 #[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
1643 #[must_use = "this returns the result of the operation, \
1644 without modifying the original"]
1646 pub const fn abs_diff(self, other: Self) -> Self {
1647 if mem::size_of::<Self>() == 1 {
1648 // Trick LLVM into generating the psadbw instruction when SSE2
1649 // is available and this function is autovectorized for u8's.
1650 (self as i32).wrapping_sub(other as i32).abs() as Self
1660 /// Calculates the multiplication of `self` and `rhs`.
1662 /// Returns a tuple of the multiplication along with a boolean
1663 /// indicating whether an arithmetic overflow would occur. If an
1664 /// overflow would have occurred then the wrapped value is returned.
1670 /// Please note that this example is shared between integer types.
1671 /// Which explains why `u32` is used here.
1674 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
1675 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
1677 #[stable(feature = "wrapping", since = "1.7.0")]
1678 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1679 #[must_use = "this returns the result of the operation, \
1680 without modifying the original"]
1682 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1683 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1687 /// Calculates the divisor when `self` is divided by `rhs`.
1689 /// Returns a tuple of the divisor along with a boolean indicating
1690 /// whether an arithmetic overflow would occur. Note that for unsigned
1691 /// integers overflow never occurs, so the second value is always
1696 /// This function will panic if `rhs` is 0.
1703 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));")]
1706 #[stable(feature = "wrapping", since = "1.7.0")]
1707 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1708 #[must_use = "this returns the result of the operation, \
1709 without modifying the original"]
1710 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1714 /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1716 /// Returns a tuple of the divisor along with a boolean indicating
1717 /// whether an arithmetic overflow would occur. Note that for unsigned
1718 /// integers overflow never occurs, so the second value is always
1720 /// Since, for the positive integers, all common
1721 /// definitions of division are equal, this
1722 /// is exactly equal to `self.overflowing_div(rhs)`.
1726 /// This function will panic if `rhs` is 0.
1733 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));")]
1736 #[stable(feature = "euclidean_division", since = "1.38.0")]
1737 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1738 #[must_use = "this returns the result of the operation, \
1739 without modifying the original"]
1740 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1744 /// Calculates the remainder when `self` is divided by `rhs`.
1746 /// Returns a tuple of the remainder after dividing along with a boolean
1747 /// indicating whether an arithmetic overflow would occur. Note that for
1748 /// unsigned integers overflow never occurs, so the second value is
1753 /// This function will panic if `rhs` is 0.
1760 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));")]
1763 #[stable(feature = "wrapping", since = "1.7.0")]
1764 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1765 #[must_use = "this returns the result of the operation, \
1766 without modifying the original"]
1767 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1771 /// Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
1773 /// Returns a tuple of the modulo after dividing along with a boolean
1774 /// indicating whether an arithmetic overflow would occur. Note that for
1775 /// unsigned integers overflow never occurs, so the second value is
1777 /// Since, for the positive integers, all common
1778 /// definitions of division are equal, this operation
1779 /// is exactly equal to `self.overflowing_rem(rhs)`.
1783 /// This function will panic if `rhs` is 0.
1790 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));")]
1793 #[stable(feature = "euclidean_division", since = "1.38.0")]
1794 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1795 #[must_use = "this returns the result of the operation, \
1796 without modifying the original"]
1797 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1801 /// Negates self in an overflowing fashion.
1803 /// Returns `!self + 1` using wrapping operations to return the value
1804 /// that represents the negation of this unsigned value. Note that for
1805 /// positive unsigned values overflow always occurs, but negating 0 does
1813 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));")]
1814 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT), ", true));")]
1817 #[stable(feature = "wrapping", since = "1.7.0")]
1818 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1819 #[must_use = "this returns the result of the operation, \
1820 without modifying the original"]
1821 pub const fn overflowing_neg(self) -> (Self, bool) {
1822 ((!self).wrapping_add(1), self != 0)
1825 /// Shifts self left by `rhs` bits.
1827 /// Returns a tuple of the shifted version of self along with a boolean
1828 /// indicating whether the shift value was larger than or equal to the
1829 /// number of bits. If the shift value is too large, then value is
1830 /// masked (N-1) where N is the number of bits, and this value is then
1831 /// used to perform the shift.
1838 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));")]
1839 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));")]
1841 #[stable(feature = "wrapping", since = "1.7.0")]
1842 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1843 #[must_use = "this returns the result of the operation, \
1844 without modifying the original"]
1846 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1847 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1850 /// Shifts self right by `rhs` bits.
1852 /// Returns a tuple of the shifted version of self along with a boolean
1853 /// indicating whether the shift value was larger than or equal to the
1854 /// number of bits. If the shift value is too large, then value is
1855 /// masked (N-1) where N is the number of bits, and this value is then
1856 /// used to perform the shift.
1863 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));")]
1864 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));")]
1866 #[stable(feature = "wrapping", since = "1.7.0")]
1867 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1868 #[must_use = "this returns the result of the operation, \
1869 without modifying the original"]
1871 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1872 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1875 /// Raises self to the power of `exp`, using exponentiation by squaring.
1877 /// Returns a tuple of the exponentiation along with a bool indicating
1878 /// whether an overflow happened.
1885 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));")]
1886 /// assert_eq!(3u8.overflowing_pow(6), (217, true));
1888 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1889 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1890 #[must_use = "this returns the result of the operation, \
1891 without modifying the original"]
1893 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1897 let mut base = self;
1898 let mut acc: Self = 1;
1899 let mut overflown = false;
1900 // Scratch space for storing results of overflowing_mul.
1905 r = acc.overflowing_mul(base);
1910 r = base.overflowing_mul(base);
1915 // since exp!=0, finally the exp must be 1.
1916 // Deal with the final bit of the exponent separately, since
1917 // squaring the base afterwards is not necessary and may cause a
1918 // needless overflow.
1919 r = acc.overflowing_mul(base);
1925 /// Raises self to the power of `exp`, using exponentiation by squaring.
1932 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".pow(5), 32);")]
1934 #[stable(feature = "rust1", since = "1.0.0")]
1935 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1936 #[must_use = "this returns the result of the operation, \
1937 without modifying the original"]
1939 #[rustc_inherit_overflow_checks]
1940 pub const fn pow(self, mut exp: u32) -> Self {
1944 let mut base = self;
1955 // since exp!=0, finally the exp must be 1.
1956 // Deal with the final bit of the exponent separately, since
1957 // squaring the base afterwards is not necessary and may cause a
1958 // needless overflow.
1962 /// Performs Euclidean division.
1964 /// Since, for the positive integers, all common
1965 /// definitions of division are equal, this
1966 /// is exactly equal to `self / rhs`.
1970 /// This function will panic if `rhs` is 0.
1977 #[doc = concat!("assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type")]
1979 #[stable(feature = "euclidean_division", since = "1.38.0")]
1980 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1981 #[must_use = "this returns the result of the operation, \
1982 without modifying the original"]
1984 #[rustc_inherit_overflow_checks]
1985 pub const fn div_euclid(self, rhs: Self) -> Self {
1990 /// Calculates the least remainder of `self (mod rhs)`.
1992 /// Since, for the positive integers, all common
1993 /// definitions of division are equal, this
1994 /// is exactly equal to `self % rhs`.
1998 /// This function will panic if `rhs` is 0.
2005 #[doc = concat!("assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type")]
2007 #[stable(feature = "euclidean_division", since = "1.38.0")]
2008 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
2009 #[must_use = "this returns the result of the operation, \
2010 without modifying the original"]
2012 #[rustc_inherit_overflow_checks]
2013 pub const fn rem_euclid(self, rhs: Self) -> Self {
2017 /// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
2019 /// This is the same as performing `self / rhs` for all unsigned integers.
2023 /// This function will panic if `rhs` is zero.
2030 /// #![feature(int_roundings)]
2031 #[doc = concat!("assert_eq!(7_", stringify!($SelfT), ".div_floor(4), 1);")]
2033 #[unstable(feature = "int_roundings", issue = "88581")]
2034 #[must_use = "this returns the result of the operation, \
2035 without modifying the original"]
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 zero.
2047 /// ## Overflow behavior
2049 /// On overflow, this function will panic if overflow checks are enabled (default in debug
2050 /// mode) and wrap if overflow checks are disabled (default in release mode).
2057 /// #![feature(int_roundings)]
2058 #[doc = concat!("assert_eq!(7_", stringify!($SelfT), ".div_ceil(4), 2);")]
2060 #[unstable(feature = "int_roundings", issue = "88581")]
2061 #[must_use = "this returns the result of the operation, \
2062 without modifying the original"]
2064 #[rustc_inherit_overflow_checks]
2065 pub const fn div_ceil(self, rhs: Self) -> Self {
2068 if r > 0 && rhs > 0 {
2075 /// Calculates the smallest value greater than or equal to `self` that
2076 /// is a multiple of `rhs`.
2080 /// This function will panic if `rhs` is zero.
2082 /// ## Overflow behavior
2084 /// On overflow, this function will panic if overflow checks are enabled (default in debug
2085 /// mode) and wrap if overflow checks are disabled (default in release mode).
2092 /// #![feature(int_roundings)]
2093 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".next_multiple_of(8), 16);")]
2094 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".next_multiple_of(8), 24);")]
2096 #[unstable(feature = "int_roundings", issue = "88581")]
2097 #[must_use = "this returns the result of the operation, \
2098 without modifying the original"]
2100 #[rustc_inherit_overflow_checks]
2101 pub const fn next_multiple_of(self, rhs: Self) -> Self {
2104 r => self + (rhs - r)
2108 /// Calculates the smallest value greater than or equal to `self` that
2109 /// is a multiple of `rhs`. Returns `None` if `rhs` is zero or the
2110 /// operation would result in overflow.
2117 /// #![feature(int_roundings)]
2118 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(16));")]
2119 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(24));")]
2120 #[doc = concat!("assert_eq!(1_", stringify!($SelfT), ".checked_next_multiple_of(0), None);")]
2121 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_multiple_of(2), None);")]
2123 #[unstable(feature = "int_roundings", issue = "88581")]
2124 #[must_use = "this returns the result of the operation, \
2125 without modifying the original"]
2127 pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
2128 match try_opt!(self.checked_rem(rhs)) {
2130 // rhs - r cannot overflow because r is smaller than rhs
2131 r => self.checked_add(rhs - r)
2135 /// Returns `true` if and only if `self == 2^k` for some `k`.
2142 #[doc = concat!("assert!(16", stringify!($SelfT), ".is_power_of_two());")]
2143 #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_power_of_two());")]
2146 #[stable(feature = "rust1", since = "1.0.0")]
2147 #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
2149 pub const fn is_power_of_two(self) -> bool {
2150 self.count_ones() == 1
2153 // Returns one less than next power of two.
2154 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
2156 // 8u8.one_less_than_next_power_of_two() == 7
2157 // 6u8.one_less_than_next_power_of_two() == 7
2159 // This method cannot overflow, as in the `next_power_of_two`
2160 // overflow cases it instead ends up returning the maximum value
2161 // of the type, and can return 0 for 0.
2163 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2164 const fn one_less_than_next_power_of_two(self) -> Self {
2165 if self <= 1 { return 0; }
2168 // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros.
2169 // That means the shift is always in-bounds, and some processors
2170 // (such as intel pre-haswell) have more efficient ctlz
2171 // intrinsics when the argument is non-zero.
2172 let z = unsafe { intrinsics::ctlz_nonzero(p) };
2176 /// Returns the smallest power of two greater than or equal to `self`.
2178 /// When return value overflows (i.e., `self > (1 << (N-1))` for type
2179 /// `uN`), it panics in debug mode and the return value is wrapped to 0 in
2180 /// release mode (the only situation in which method can return 0).
2187 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);")]
2188 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);")]
2190 #[stable(feature = "rust1", since = "1.0.0")]
2191 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2192 #[must_use = "this returns the result of the operation, \
2193 without modifying the original"]
2195 #[rustc_inherit_overflow_checks]
2196 pub const fn next_power_of_two(self) -> Self {
2197 self.one_less_than_next_power_of_two() + 1
2200 /// Returns the smallest power of two greater than or equal to `n`. If
2201 /// the next power of two is greater than the type's maximum value,
2202 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
2209 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_next_power_of_two(), Some(2));")]
2210 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));")]
2211 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_power_of_two(), None);")]
2214 #[stable(feature = "rust1", since = "1.0.0")]
2215 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2216 #[must_use = "this returns the result of the operation, \
2217 without modifying the original"]
2218 pub const fn checked_next_power_of_two(self) -> Option<Self> {
2219 self.one_less_than_next_power_of_two().checked_add(1)
2222 /// Returns the smallest power of two greater than or equal to `n`. If
2223 /// the next power of two is greater than the type's maximum value,
2224 /// the return value is wrapped to `0`.
2231 /// #![feature(wrapping_next_power_of_two)]
2233 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);")]
2234 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);")]
2235 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_next_power_of_two(), 0);")]
2238 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
2239 reason = "needs decision on wrapping behaviour")]
2240 #[rustc_const_unstable(feature = "wrapping_next_power_of_two", issue = "32463")]
2241 #[must_use = "this returns the result of the operation, \
2242 without modifying the original"]
2243 pub const fn wrapping_next_power_of_two(self) -> Self {
2244 self.one_less_than_next_power_of_two().wrapping_add(1)
2247 /// Return the memory representation of this integer as a byte array in
2248 /// big-endian (network) byte order.
2250 #[doc = $to_xe_bytes_doc]
2255 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();")]
2256 #[doc = concat!("assert_eq!(bytes, ", $be_bytes, ");")]
2258 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2259 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2260 #[must_use = "this returns the result of the operation, \
2261 without modifying the original"]
2263 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2264 self.to_be().to_ne_bytes()
2267 /// Return the memory representation of this integer as a byte array in
2268 /// little-endian byte order.
2270 #[doc = $to_xe_bytes_doc]
2275 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();")]
2276 #[doc = concat!("assert_eq!(bytes, ", $le_bytes, ");")]
2278 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2279 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2280 #[must_use = "this returns the result of the operation, \
2281 without modifying the original"]
2283 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2284 self.to_le().to_ne_bytes()
2287 /// Return the memory representation of this integer as a byte array in
2288 /// native byte order.
2290 /// As the target platform's native endianness is used, portable code
2291 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2294 #[doc = $to_xe_bytes_doc]
2296 /// [`to_be_bytes`]: Self::to_be_bytes
2297 /// [`to_le_bytes`]: Self::to_le_bytes
2302 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();")]
2305 /// if cfg!(target_endian = "big") {
2306 #[doc = concat!(" ", $be_bytes)]
2308 #[doc = concat!(" ", $le_bytes)]
2312 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2313 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2314 #[must_use = "this returns the result of the operation, \
2315 without modifying the original"]
2316 // SAFETY: const sound because integers are plain old datatypes so we can always
2317 // transmute them to arrays of bytes
2319 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2320 // SAFETY: integers are plain old datatypes so we can always transmute them to
2322 unsafe { mem::transmute(self) }
2325 /// Create a native endian integer value from its representation
2326 /// as a byte array in big endian.
2328 #[doc = $from_xe_bytes_doc]
2333 #[doc = concat!("let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");")]
2334 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2337 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2340 #[doc = concat!("fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2341 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2343 #[doc = concat!(" ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())")]
2346 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2347 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2350 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2351 Self::from_be(Self::from_ne_bytes(bytes))
2354 /// Create a native endian integer value from its representation
2355 /// as a byte array in little endian.
2357 #[doc = $from_xe_bytes_doc]
2362 #[doc = concat!("let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");")]
2363 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2366 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2369 #[doc = concat!("fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2370 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2372 #[doc = concat!(" ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())")]
2375 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2376 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2379 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2380 Self::from_le(Self::from_ne_bytes(bytes))
2383 /// Create a native endian integer value from its memory representation
2384 /// as a byte array in native endianness.
2386 /// As the target platform's native endianness is used, portable code
2387 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2388 /// appropriate instead.
2390 /// [`from_be_bytes`]: Self::from_be_bytes
2391 /// [`from_le_bytes`]: Self::from_le_bytes
2393 #[doc = $from_xe_bytes_doc]
2398 #[doc = concat!("let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {")]
2399 #[doc = concat!(" ", $be_bytes, "")]
2401 #[doc = concat!(" ", $le_bytes, "")]
2403 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2406 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2409 #[doc = concat!("fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2410 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2412 #[doc = concat!(" ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())")]
2415 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2416 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2418 // SAFETY: const sound because integers are plain old datatypes so we can always
2419 // transmute to them
2421 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2422 // SAFETY: integers are plain old datatypes so we can always transmute to them
2423 unsafe { mem::transmute(bytes) }
2426 /// New code should prefer to use
2427 #[doc = concat!("[`", stringify!($SelfT), "::MIN", "`] instead.")]
2429 /// Returns the smallest 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 #[deprecated(since = "TBD", note = "replaced by the `MIN` associated constant on this type")]
2435 pub const fn min_value() -> Self { Self::MIN }
2437 /// New code should prefer to use
2438 #[doc = concat!("[`", stringify!($SelfT), "::MAX", "`] instead.")]
2440 /// Returns the largest value that can be represented by this integer type.
2441 #[stable(feature = "rust1", since = "1.0.0")]
2444 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2445 #[deprecated(since = "TBD", note = "replaced by the `MAX` associated constant on this type")]
2446 pub const fn max_value() -> Self { Self::MAX }