1 macro_rules! uint_impl {
2 ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr,
3 $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
4 $reversed:expr, $le_bytes:expr, $be_bytes:expr,
5 $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
7 concat!("The smallest value that can be represented by this integer type.
14 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MIN, 0);", $EndFeature, "
16 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
17 pub const MIN: Self = 0;
21 concat!("The largest value that can be represented by this integer type.
28 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($MaxV), ");",
31 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
32 pub const MAX: Self = !0;
36 concat!("The size of this integer type in bits.
41 ", $Feature, "#![feature(int_bits_const)]
42 assert_eq!(", stringify!($SelfT), "::BITS, ", stringify!($BITS), ");",
45 #[unstable(feature = "int_bits_const", issue = "76904")]
46 pub const BITS: u32 = $BITS;
50 concat!("Converts a string slice in a given base to an integer.
52 The string is expected to be an optional `+` sign
54 Leading and trailing whitespace represent an error.
55 Digits are a subset of these characters, depending on `radix`:
63 This function panics if `radix` is not in the range from 2 to 36.
70 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
73 #[stable(feature = "rust1", since = "1.0.0")]
74 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
75 from_str_radix(src, radix)
80 concat!("Returns the number of ones in the binary representation of `self`.
87 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
89 assert_eq!(n.count_ones(), 3);", $EndFeature, "
91 #[stable(feature = "rust1", since = "1.0.0")]
92 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
93 #[doc(alias = "popcount")]
94 #[doc(alias = "popcnt")]
96 pub const fn count_ones(self) -> u32 {
97 intrinsics::ctpop(self as $ActualT) as u32
102 concat!("Returns the number of zeros in the binary representation of `self`.
109 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX.count_zeros(), 0);", $EndFeature, "
111 #[stable(feature = "rust1", since = "1.0.0")]
112 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
114 pub const fn count_zeros(self) -> u32 {
120 concat!("Returns the number of leading zeros in the binary representation of `self`.
127 ", $Feature, "let n = ", stringify!($SelfT), "::MAX >> 2;
129 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
131 #[stable(feature = "rust1", since = "1.0.0")]
132 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
134 pub const fn leading_zeros(self) -> u32 {
135 intrinsics::ctlz(self as $ActualT) as u32
140 concat!("Returns the number of trailing zeros in the binary representation
148 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
150 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
152 #[stable(feature = "rust1", since = "1.0.0")]
153 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
155 pub const fn trailing_zeros(self) -> u32 {
156 intrinsics::cttz(self) as u32
161 concat!("Returns the number of leading ones in the binary representation of `self`.
168 ", $Feature, "let n = !(", stringify!($SelfT), "::MAX >> 2);
170 assert_eq!(n.leading_ones(), 2);", $EndFeature, "
172 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
173 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
175 pub const fn leading_ones(self) -> u32 {
176 (!self).leading_zeros()
181 concat!("Returns the number of trailing ones in the binary representation
189 ", $Feature, "let n = 0b1010111", stringify!($SelfT), ";
191 assert_eq!(n.trailing_ones(), 3);", $EndFeature, "
193 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
194 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
196 pub const fn trailing_ones(self) -> u32 {
197 (!self).trailing_zeros()
202 concat!("Shifts the bits to the left by a specified amount, `n`,
203 wrapping the truncated bits to the end of the resulting integer.
205 Please note this isn't the same operation as the `<<` shifting operator!
212 let n = ", $rot_op, stringify!($SelfT), ";
213 let m = ", $rot_result, ";
215 assert_eq!(n.rotate_left(", $rot, "), m);
217 #[stable(feature = "rust1", since = "1.0.0")]
218 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
219 #[must_use = "this returns the result of the operation, \
220 without modifying the original"]
222 pub const fn rotate_left(self, n: u32) -> Self {
223 intrinsics::rotate_left(self, n as $SelfT)
228 concat!("Shifts the bits to the right by a specified amount, `n`,
229 wrapping the truncated bits to the beginning of the resulting
232 Please note this isn't the same operation as the `>>` shifting operator!
239 let n = ", $rot_result, stringify!($SelfT), ";
240 let m = ", $rot_op, ";
242 assert_eq!(n.rotate_right(", $rot, "), m);
244 #[stable(feature = "rust1", since = "1.0.0")]
245 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
246 #[must_use = "this returns the result of the operation, \
247 without modifying the original"]
249 pub const fn rotate_right(self, n: u32) -> Self {
250 intrinsics::rotate_right(self, n as $SelfT)
256 Reverses the byte order of the integer.
263 let n = ", $swap_op, stringify!($SelfT), ";
264 let m = n.swap_bytes();
266 assert_eq!(m, ", $swapped, ");
268 #[stable(feature = "rust1", since = "1.0.0")]
269 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
271 pub const fn swap_bytes(self) -> Self {
272 intrinsics::bswap(self as $ActualT) as Self
277 concat!("Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
278 second least-significant bit becomes second most-significant bit, etc.
285 let n = ", $swap_op, stringify!($SelfT), ";
286 let m = n.reverse_bits();
288 assert_eq!(m, ", $reversed, ");
289 assert_eq!(0, 0", stringify!($SelfT), ".reverse_bits());
291 #[stable(feature = "reverse_bits", since = "1.37.0")]
292 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
295 pub const fn reverse_bits(self) -> Self {
296 intrinsics::bitreverse(self as $ActualT) as Self
301 concat!("Converts an integer from big endian to the target's endianness.
303 On big endian this is a no-op. On little endian the bytes are
311 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
313 if cfg!(target_endian = \"big\") {
314 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
316 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
319 #[stable(feature = "rust1", since = "1.0.0")]
320 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
322 pub const fn from_be(x: Self) -> Self {
323 #[cfg(target_endian = "big")]
327 #[cfg(not(target_endian = "big"))]
335 concat!("Converts an integer from little endian to the target's endianness.
337 On little endian this is a no-op. On big endian the bytes are
345 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
347 if cfg!(target_endian = \"little\") {
348 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
350 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
353 #[stable(feature = "rust1", since = "1.0.0")]
354 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
356 pub const fn from_le(x: Self) -> Self {
357 #[cfg(target_endian = "little")]
361 #[cfg(not(target_endian = "little"))]
369 concat!("Converts `self` to big endian from the target's endianness.
371 On big endian this is a no-op. On little endian the bytes are
379 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
381 if cfg!(target_endian = \"big\") {
382 assert_eq!(n.to_be(), n)
384 assert_eq!(n.to_be(), n.swap_bytes())
387 #[stable(feature = "rust1", since = "1.0.0")]
388 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
390 pub const fn to_be(self) -> Self { // or not to be?
391 #[cfg(target_endian = "big")]
395 #[cfg(not(target_endian = "big"))]
403 concat!("Converts `self` to little endian from the target's endianness.
405 On little endian this is a no-op. On big endian the bytes are
413 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
415 if cfg!(target_endian = \"little\") {
416 assert_eq!(n.to_le(), n)
418 assert_eq!(n.to_le(), n.swap_bytes())
421 #[stable(feature = "rust1", since = "1.0.0")]
422 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
424 pub const fn to_le(self) -> Self {
425 #[cfg(target_endian = "little")]
429 #[cfg(not(target_endian = "little"))]
437 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
438 if overflow occurred.
445 ", $Feature, "assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(1), ",
446 "Some(", stringify!($SelfT), "::MAX - 1));
447 assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);", $EndFeature, "
449 #[stable(feature = "rust1", since = "1.0.0")]
450 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
451 #[must_use = "this returns the result of the operation, \
452 without modifying the original"]
454 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
455 let (a, b) = self.overflowing_add(rhs);
456 if unlikely!(b) {None} else {Some(a)}
461 concat!("Unchecked integer addition. Computes `self + rhs`, assuming overflow
462 cannot occur. This results in undefined behavior when `self + rhs > ", stringify!($SelfT),
463 "::MAX` or `self + rhs < ", stringify!($SelfT), "::MIN`."),
465 feature = "unchecked_math",
466 reason = "niche optimization path",
469 #[must_use = "this returns the result of the operation, \
470 without modifying the original"]
472 pub unsafe fn unchecked_add(self, rhs: Self) -> Self {
473 // SAFETY: the caller must uphold the safety contract for
475 unsafe { intrinsics::unchecked_add(self, rhs) }
480 concat!("Checked integer subtraction. Computes `self - rhs`, returning
481 `None` if overflow occurred.
488 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
489 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
491 #[stable(feature = "rust1", since = "1.0.0")]
492 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
493 #[must_use = "this returns the result of the operation, \
494 without modifying the original"]
496 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
497 let (a, b) = self.overflowing_sub(rhs);
498 if unlikely!(b) {None} else {Some(a)}
503 concat!("Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
504 cannot occur. This results in undefined behavior when `self - rhs > ", stringify!($SelfT),
505 "::MAX` or `self - rhs < ", stringify!($SelfT), "::MIN`."),
507 feature = "unchecked_math",
508 reason = "niche optimization path",
511 #[must_use = "this returns the result of the operation, \
512 without modifying the original"]
514 pub unsafe fn unchecked_sub(self, rhs: Self) -> Self {
515 // SAFETY: the caller must uphold the safety contract for
517 unsafe { intrinsics::unchecked_sub(self, rhs) }
522 concat!("Checked integer multiplication. Computes `self * rhs`, returning
523 `None` if overflow occurred.
530 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
531 assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);", $EndFeature, "
533 #[stable(feature = "rust1", since = "1.0.0")]
534 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
535 #[must_use = "this returns the result of the operation, \
536 without modifying the original"]
538 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
539 let (a, b) = self.overflowing_mul(rhs);
540 if unlikely!(b) {None} else {Some(a)}
545 concat!("Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
546 cannot occur. This results in undefined behavior when `self * rhs > ", stringify!($SelfT),
547 "::MAX` or `self * rhs < ", stringify!($SelfT), "::MIN`."),
549 feature = "unchecked_math",
550 reason = "niche optimization path",
553 #[must_use = "this returns the result of the operation, \
554 without modifying the original"]
556 pub unsafe fn unchecked_mul(self, rhs: Self) -> Self {
557 // SAFETY: the caller must uphold the safety contract for
559 unsafe { intrinsics::unchecked_mul(self, rhs) }
564 concat!("Checked integer division. Computes `self / rhs`, returning `None`
572 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
573 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
575 #[stable(feature = "rust1", since = "1.0.0")]
576 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
577 #[must_use = "this returns the result of the operation, \
578 without modifying the original"]
580 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
581 if unlikely!(rhs == 0) {
584 // SAFETY: div by zero has been checked above and unsigned types have no other
585 // failure modes for division
586 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
592 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
600 assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));
601 assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);
603 #[stable(feature = "euclidean_division", since = "1.38.0")]
604 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
605 #[must_use = "this returns the result of the operation, \
606 without modifying the original"]
608 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
609 if unlikely!(rhs == 0) {
612 Some(self.div_euclid(rhs))
619 concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
627 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
628 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
630 #[stable(feature = "wrapping", since = "1.7.0")]
631 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
632 #[must_use = "this returns the result of the operation, \
633 without modifying the original"]
635 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
636 if unlikely!(rhs == 0) {
639 // SAFETY: div by zero has been checked above and unsigned types have no other
640 // failure modes for division
641 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
647 concat!("Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
655 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
656 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
658 #[stable(feature = "euclidean_division", since = "1.38.0")]
659 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
660 #[must_use = "this returns the result of the operation, \
661 without modifying the original"]
663 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
664 if unlikely!(rhs == 0) {
667 Some(self.rem_euclid(rhs))
673 concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
676 Note that negating any positive integer will overflow.
683 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
684 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
686 #[stable(feature = "wrapping", since = "1.7.0")]
687 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
689 pub const fn checked_neg(self) -> Option<Self> {
690 let (a, b) = self.overflowing_neg();
691 if unlikely!(b) {None} else {Some(a)}
696 concat!("Checked shift left. Computes `self << rhs`, returning `None`
697 if `rhs` is larger than or equal to the number of bits in `self`.
704 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
705 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
707 #[stable(feature = "wrapping", since = "1.7.0")]
708 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
709 #[must_use = "this returns the result of the operation, \
710 without modifying the original"]
712 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
713 let (a, b) = self.overflowing_shl(rhs);
714 if unlikely!(b) {None} else {Some(a)}
719 concat!("Checked shift right. Computes `self >> rhs`, returning `None`
720 if `rhs` is larger than or equal to the number of bits in `self`.
727 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
728 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
730 #[stable(feature = "wrapping", since = "1.7.0")]
731 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
732 #[must_use = "this returns the result of the operation, \
733 without modifying the original"]
735 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
736 let (a, b) = self.overflowing_shr(rhs);
737 if unlikely!(b) {None} else {Some(a)}
742 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
750 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
751 assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);", $EndFeature, "
753 #[stable(feature = "no_panic_pow", since = "1.34.0")]
754 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
755 #[must_use = "this returns the result of the operation, \
756 without modifying the original"]
758 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
763 let mut acc: Self = 1;
767 acc = try_opt!(acc.checked_mul(base));
770 base = try_opt!(base.checked_mul(base));
773 // since exp!=0, finally the exp must be 1.
774 // Deal with the final bit of the exponent separately, since
775 // squaring the base afterwards is not necessary and may cause a
776 // needless overflow.
778 Some(try_opt!(acc.checked_mul(base)))
783 concat!("Saturating integer addition. Computes `self + rhs`, saturating at
784 the numeric bounds instead of overflowing.
791 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
792 assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(127), ", stringify!($SelfT), "::MAX);",
796 #[stable(feature = "rust1", since = "1.0.0")]
797 #[must_use = "this returns the result of the operation, \
798 without modifying the original"]
799 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
801 pub const fn saturating_add(self, rhs: Self) -> Self {
802 intrinsics::saturating_add(self, rhs)
807 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
808 at the numeric bounds instead of overflowing.
815 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
816 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
818 #[stable(feature = "rust1", since = "1.0.0")]
819 #[must_use = "this returns the result of the operation, \
820 without modifying the original"]
821 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
823 pub const fn saturating_sub(self, rhs: Self) -> Self {
824 intrinsics::saturating_sub(self, rhs)
829 concat!("Saturating integer multiplication. Computes `self * rhs`,
830 saturating at the numeric bounds instead of overflowing.
838 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
839 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
840 "::MAX);", $EndFeature, "
842 #[stable(feature = "wrapping", since = "1.7.0")]
843 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
844 #[must_use = "this returns the result of the operation, \
845 without modifying the original"]
847 pub const fn saturating_mul(self, rhs: Self) -> Self {
848 match self.checked_mul(rhs) {
856 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
857 saturating at the numeric bounds instead of overflowing.
865 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
866 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
869 #[stable(feature = "no_panic_pow", since = "1.34.0")]
870 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
871 #[must_use = "this returns the result of the operation, \
872 without modifying the original"]
874 pub const fn saturating_pow(self, exp: u32) -> Self {
875 match self.checked_pow(exp) {
883 concat!("Wrapping (modular) addition. Computes `self + rhs`,
884 wrapping around at the boundary of the type.
891 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
892 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);",
895 #[stable(feature = "rust1", since = "1.0.0")]
896 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
897 #[must_use = "this returns the result of the operation, \
898 without modifying the original"]
900 pub const fn wrapping_add(self, rhs: Self) -> Self {
901 intrinsics::wrapping_add(self, rhs)
906 concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
907 wrapping around at the boundary of the type.
914 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
915 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::MAX), 101);",
918 #[stable(feature = "rust1", since = "1.0.0")]
919 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
920 #[must_use = "this returns the result of the operation, \
921 without modifying the original"]
923 pub const fn wrapping_sub(self, rhs: Self) -> Self {
924 intrinsics::wrapping_sub(self, rhs)
928 /// Wrapping (modular) multiplication. Computes `self *
929 /// rhs`, wrapping around at the boundary of the type.
935 /// Please note that this example is shared between integer types.
936 /// Which explains why `u8` is used here.
939 /// assert_eq!(10u8.wrapping_mul(12), 120);
940 /// assert_eq!(25u8.wrapping_mul(12), 44);
942 #[stable(feature = "rust1", since = "1.0.0")]
943 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
944 #[must_use = "this returns the result of the operation, \
945 without modifying the original"]
947 pub const fn wrapping_mul(self, rhs: Self) -> Self {
948 intrinsics::wrapping_mul(self, rhs)
952 concat!("Wrapping (modular) division. Computes `self / rhs`.
953 Wrapped division on unsigned types is just normal division.
954 There's no way wrapping could ever happen.
955 This function exists, so that all operations
956 are accounted for in the wrapping operations.
963 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
965 #[stable(feature = "num_wrapping", since = "1.2.0")]
966 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
967 #[must_use = "this returns the result of the operation, \
968 without modifying the original"]
970 pub const fn wrapping_div(self, rhs: Self) -> Self {
976 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
977 Wrapped division on unsigned types is just normal division.
978 There's no way wrapping could ever happen.
979 This function exists, so that all operations
980 are accounted for in the wrapping operations.
981 Since, for the positive integers, all common
982 definitions of division are equal, this
983 is exactly equal to `self.wrapping_div(rhs)`.
990 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
992 #[stable(feature = "euclidean_division", since = "1.38.0")]
993 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
994 #[must_use = "this returns the result of the operation, \
995 without modifying the original"]
997 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
1003 concat!("Wrapping (modular) remainder. Computes `self % rhs`.
1004 Wrapped remainder calculation on unsigned types is
1005 just the regular remainder calculation.
1006 There's no way wrapping could ever happen.
1007 This function exists, so that all operations
1008 are accounted for in the wrapping operations.
1015 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
1017 #[stable(feature = "num_wrapping", since = "1.2.0")]
1018 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
1019 #[must_use = "this returns the result of the operation, \
1020 without modifying the original"]
1022 pub const fn wrapping_rem(self, rhs: Self) -> Self {
1028 concat!("Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
1029 Wrapped modulo calculation on unsigned types is
1030 just the regular remainder calculation.
1031 There's no way wrapping could ever happen.
1032 This function exists, so that all operations
1033 are accounted for in the wrapping operations.
1034 Since, for the positive integers, all common
1035 definitions of division are equal, this
1036 is exactly equal to `self.wrapping_rem(rhs)`.
1043 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
1045 #[stable(feature = "euclidean_division", since = "1.38.0")]
1046 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1047 #[must_use = "this returns the result of the operation, \
1048 without modifying the original"]
1050 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1055 /// Wrapping (modular) negation. Computes `-self`,
1056 /// wrapping around at the boundary of the type.
1058 /// Since unsigned types do not have negative equivalents
1059 /// all applications of this function will wrap (except for `-0`).
1060 /// For values smaller than the corresponding signed type's maximum
1061 /// the result is the same as casting the corresponding signed value.
1062 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
1063 /// `MAX` is the corresponding signed type's maximum.
1069 /// Please note that this example is shared between integer types.
1070 /// Which explains why `i8` is used here.
1073 /// assert_eq!(100i8.wrapping_neg(), -100);
1074 /// assert_eq!((-128i8).wrapping_neg(), -128);
1076 #[stable(feature = "num_wrapping", since = "1.2.0")]
1077 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1079 pub const fn wrapping_neg(self) -> Self {
1080 self.overflowing_neg().0
1084 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1085 where `mask` removes any high-order bits of `rhs` that
1086 would cause the shift to exceed the bitwidth of the type.
1088 Note that this is *not* the same as a rotate-left; the
1089 RHS of a wrapping shift-left is restricted to the range
1090 of the type, rather than the bits shifted out of the LHS
1091 being returned to the other end. The primitive integer
1092 types all implement a [`rotate_left`](#method.rotate_left) function,
1093 which may be what you want instead.
1100 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
1101 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
1103 #[stable(feature = "num_wrapping", since = "1.2.0")]
1104 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1105 #[must_use = "this returns the result of the operation, \
1106 without modifying the original"]
1108 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1109 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1112 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1118 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
1119 where `mask` removes any high-order bits of `rhs` that
1120 would cause the shift to exceed the bitwidth of the type.
1122 Note that this is *not* the same as a rotate-right; the
1123 RHS of a wrapping shift-right is restricted to the range
1124 of the type, rather than the bits shifted out of the LHS
1125 being returned to the other end. The primitive integer
1126 types all implement a [`rotate_right`](#method.rotate_right) function,
1127 which may be what you want instead.
1134 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
1135 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
1137 #[stable(feature = "num_wrapping", since = "1.2.0")]
1138 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1139 #[must_use = "this returns the result of the operation, \
1140 without modifying the original"]
1142 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1143 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1146 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1152 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1153 wrapping around at the boundary of the type.
1160 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
1161 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
1163 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1164 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1165 #[must_use = "this returns the result of the operation, \
1166 without modifying the original"]
1168 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
1172 let mut base = self;
1173 let mut acc: Self = 1;
1177 acc = acc.wrapping_mul(base);
1180 base = base.wrapping_mul(base);
1183 // since exp!=0, finally the exp must be 1.
1184 // Deal with the final bit of the exponent separately, since
1185 // squaring the base afterwards is not necessary and may cause a
1186 // needless overflow.
1187 acc.wrapping_mul(base)
1192 concat!("Calculates `self` + `rhs`
1194 Returns a tuple of the addition along with a boolean indicating
1195 whether an arithmetic overflow would occur. If an overflow would
1196 have occurred then the wrapped value is returned.
1204 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1205 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
1207 #[stable(feature = "wrapping", since = "1.7.0")]
1208 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1209 #[must_use = "this returns the result of the operation, \
1210 without modifying the original"]
1212 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1213 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1219 concat!("Calculates `self` - `rhs`
1221 Returns a tuple of the subtraction along with a boolean indicating
1222 whether an arithmetic overflow would occur. If an overflow would
1223 have occurred then the wrapped value is returned.
1231 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
1232 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
1235 #[stable(feature = "wrapping", since = "1.7.0")]
1236 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1237 #[must_use = "this returns the result of the operation, \
1238 without modifying the original"]
1240 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1241 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1246 /// Calculates the multiplication of `self` and `rhs`.
1248 /// Returns a tuple of the multiplication along with a boolean
1249 /// indicating whether an arithmetic overflow would occur. If an
1250 /// overflow would have occurred then the wrapped value is returned.
1256 /// Please note that this example is shared between integer types.
1257 /// Which explains why `u32` is used here.
1260 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
1261 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
1263 #[stable(feature = "wrapping", since = "1.7.0")]
1264 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1265 #[must_use = "this returns the result of the operation, \
1266 without modifying the original"]
1268 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1269 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1274 concat!("Calculates the divisor when `self` is divided by `rhs`.
1276 Returns a tuple of the divisor along with a boolean indicating
1277 whether an arithmetic overflow would occur. Note that for unsigned
1278 integers overflow never occurs, so the second value is always
1283 This function will panic if `rhs` is 0.
1290 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
1293 #[stable(feature = "wrapping", since = "1.7.0")]
1294 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
1295 #[must_use = "this returns the result of the operation, \
1296 without modifying the original"]
1297 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1303 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1305 Returns a tuple of the divisor along with a boolean indicating
1306 whether an arithmetic overflow would occur. Note that for unsigned
1307 integers overflow never occurs, so the second value is always
1309 Since, for the positive integers, all common
1310 definitions of division are equal, this
1311 is exactly equal to `self.overflowing_div(rhs)`.
1315 This function will panic if `rhs` is 0.
1322 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
1325 #[stable(feature = "euclidean_division", since = "1.38.0")]
1326 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1327 #[must_use = "this returns the result of the operation, \
1328 without modifying the original"]
1329 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1335 concat!("Calculates the remainder when `self` is divided by `rhs`.
1337 Returns a tuple of the remainder after dividing along with a boolean
1338 indicating whether an arithmetic overflow would occur. Note that for
1339 unsigned integers overflow never occurs, so the second value is
1344 This function will panic if `rhs` is 0.
1351 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
1354 #[stable(feature = "wrapping", since = "1.7.0")]
1355 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
1356 #[must_use = "this returns the result of the operation, \
1357 without modifying the original"]
1358 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1364 concat!("Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
1366 Returns a tuple of the modulo after dividing along with a boolean
1367 indicating whether an arithmetic overflow would occur. Note that for
1368 unsigned integers overflow never occurs, so the second value is
1370 Since, for the positive integers, all common
1371 definitions of division are equal, this operation
1372 is exactly equal to `self.overflowing_rem(rhs)`.
1376 This function will panic if `rhs` is 0.
1383 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
1386 #[stable(feature = "euclidean_division", since = "1.38.0")]
1387 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1388 #[must_use = "this returns the result of the operation, \
1389 without modifying the original"]
1390 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1396 concat!("Negates self in an overflowing fashion.
1398 Returns `!self + 1` using wrapping operations to return the value
1399 that represents the negation of this unsigned value. Note that for
1400 positive unsigned values overflow always occurs, but negating 0 does
1408 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
1409 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
1410 ", true));", $EndFeature, "
1413 #[stable(feature = "wrapping", since = "1.7.0")]
1414 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1415 pub const fn overflowing_neg(self) -> (Self, bool) {
1416 ((!self).wrapping_add(1), self != 0)
1421 concat!("Shifts self left by `rhs` bits.
1423 Returns a tuple of the shifted version of self along with a boolean
1424 indicating whether the shift value was larger than or equal to the
1425 number of bits. If the shift value is too large, then value is
1426 masked (N-1) where N is the number of bits, and this value is then
1427 used to perform the shift.
1434 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
1435 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
1437 #[stable(feature = "wrapping", since = "1.7.0")]
1438 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1439 #[must_use = "this returns the result of the operation, \
1440 without modifying the original"]
1442 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1443 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1448 concat!("Shifts self right by `rhs` bits.
1450 Returns a tuple of the shifted version of self along with a boolean
1451 indicating whether the shift value was larger than or equal to the
1452 number of bits. If the shift value is too large, then value is
1453 masked (N-1) where N is the number of bits, and this value is then
1454 used to perform the shift.
1461 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1462 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
1464 #[stable(feature = "wrapping", since = "1.7.0")]
1465 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1466 #[must_use = "this returns the result of the operation, \
1467 without modifying the original"]
1469 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1470 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1475 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1477 Returns a tuple of the exponentiation along with a bool indicating
1478 whether an overflow happened.
1485 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
1486 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
1488 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1489 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1490 #[must_use = "this returns the result of the operation, \
1491 without modifying the original"]
1493 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1497 let mut base = self;
1498 let mut acc: Self = 1;
1499 let mut overflown = false;
1500 // Scratch space for storing results of overflowing_mul.
1505 r = acc.overflowing_mul(base);
1510 r = base.overflowing_mul(base);
1515 // since exp!=0, finally the exp must be 1.
1516 // Deal with the final bit of the exponent separately, since
1517 // squaring the base afterwards is not necessary and may cause a
1518 // needless overflow.
1519 r = acc.overflowing_mul(base);
1527 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1534 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
1536 #[stable(feature = "rust1", since = "1.0.0")]
1537 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1538 #[must_use = "this returns the result of the operation, \
1539 without modifying the original"]
1541 #[rustc_inherit_overflow_checks]
1542 pub const fn pow(self, mut exp: u32) -> Self {
1546 let mut base = self;
1557 // since exp!=0, finally the exp must be 1.
1558 // Deal with the final bit of the exponent separately, since
1559 // squaring the base afterwards is not necessary and may cause a
1560 // needless overflow.
1566 concat!("Performs Euclidean division.
1568 Since, for the positive integers, all common
1569 definitions of division are equal, this
1570 is exactly equal to `self / rhs`.
1574 This function will panic if `rhs` is 0.
1581 assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type
1583 #[stable(feature = "euclidean_division", since = "1.38.0")]
1584 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1585 #[must_use = "this returns the result of the operation, \
1586 without modifying the original"]
1588 #[rustc_inherit_overflow_checks]
1589 pub const fn div_euclid(self, rhs: Self) -> Self {
1596 concat!("Calculates the least remainder of `self (mod rhs)`.
1598 Since, for the positive integers, all common
1599 definitions of division are equal, this
1600 is exactly equal to `self % rhs`.
1604 This function will panic if `rhs` is 0.
1611 assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type
1613 #[stable(feature = "euclidean_division", since = "1.38.0")]
1614 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1615 #[must_use = "this returns the result of the operation, \
1616 without modifying the original"]
1618 #[rustc_inherit_overflow_checks]
1619 pub const fn rem_euclid(self, rhs: Self) -> Self {
1625 concat!("Returns `true` if and only if `self == 2^k` for some `k`.
1632 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
1633 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
1635 #[stable(feature = "rust1", since = "1.0.0")]
1636 #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
1638 pub const fn is_power_of_two(self) -> bool {
1639 self.count_ones() == 1
1643 // Returns one less than next power of two.
1644 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
1646 // 8u8.one_less_than_next_power_of_two() == 7
1647 // 6u8.one_less_than_next_power_of_two() == 7
1649 // This method cannot overflow, as in the `next_power_of_two`
1650 // overflow cases it instead ends up returning the maximum value
1651 // of the type, and can return 0 for 0.
1653 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1654 const fn one_less_than_next_power_of_two(self) -> Self {
1655 if self <= 1 { return 0; }
1658 // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros.
1659 // That means the shift is always in-bounds, and some processors
1660 // (such as intel pre-haswell) have more efficient ctlz
1661 // intrinsics when the argument is non-zero.
1662 let z = unsafe { intrinsics::ctlz_nonzero(p) };
1667 concat!("Returns the smallest power of two greater than or equal to `self`.
1669 When return value overflows (i.e., `self > (1 << (N-1))` for type
1670 `uN`), it panics in debug mode and return value is wrapped to 0 in
1671 release mode (the only situation in which method can return 0).
1678 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
1679 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
1681 #[stable(feature = "rust1", since = "1.0.0")]
1682 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1684 #[rustc_inherit_overflow_checks]
1685 pub const fn next_power_of_two(self) -> Self {
1686 self.one_less_than_next_power_of_two() + 1
1691 concat!("Returns the smallest power of two greater than or equal to `n`. If
1692 the next power of two is greater than the type's maximum value,
1693 `None` is returned, otherwise the power of two is wrapped in `Some`.
1700 ", $Feature, "assert_eq!(2", stringify!($SelfT),
1701 ".checked_next_power_of_two(), Some(2));
1702 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
1703 assert_eq!(", stringify!($SelfT), "::MAX.checked_next_power_of_two(), None);",
1707 #[stable(feature = "rust1", since = "1.0.0")]
1708 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1709 pub const fn checked_next_power_of_two(self) -> Option<Self> {
1710 self.one_less_than_next_power_of_two().checked_add(1)
1715 concat!("Returns the smallest power of two greater than or equal to `n`. If
1716 the next power of two is greater than the type's maximum value,
1717 the return value is wrapped to `0`.
1724 #![feature(wrapping_next_power_of_two)]
1726 assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);
1727 assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);
1728 assert_eq!(", stringify!($SelfT), "::MAX.wrapping_next_power_of_two(), 0);",
1731 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
1732 reason = "needs decision on wrapping behaviour")]
1733 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1734 pub const fn wrapping_next_power_of_two(self) -> Self {
1735 self.one_less_than_next_power_of_two().wrapping_add(1)
1740 concat!("Return the memory representation of this integer as a byte array in
1741 big-endian (network) byte order.
1748 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
1749 assert_eq!(bytes, ", $be_bytes, ");
1751 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
1752 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
1754 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
1755 self.to_be().to_ne_bytes()
1760 concat!("Return the memory representation of this integer as a byte array in
1761 little-endian byte order.
1768 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
1769 assert_eq!(bytes, ", $le_bytes, ");
1771 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
1772 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
1774 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
1775 self.to_le().to_ne_bytes()
1781 Return the memory representation of this integer as a byte array in
1784 As the target platform's native endianness is used, portable code
1785 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
1790 [`to_be_bytes`]: #method.to_be_bytes
1791 [`to_le_bytes`]: #method.to_le_bytes
1796 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
1799 if cfg!(target_endian = \"big\") {
1806 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
1807 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
1808 // SAFETY: const sound because integers are plain old datatypes so we can always
1809 // transmute them to arrays of bytes
1810 #[rustc_allow_const_fn_unstable(const_fn_transmute)]
1812 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
1813 // SAFETY: integers are plain old datatypes so we can always transmute them to
1815 unsafe { mem::transmute(self) }
1821 Return the memory representation of this integer as a byte array in
1824 [`to_ne_bytes`] should be preferred over this whenever possible.
1826 [`to_ne_bytes`]: #method.to_ne_bytes
1833 #![feature(num_as_ne_bytes)]
1834 let num = ", $swap_op, stringify!($SelfT), ";
1835 let bytes = num.as_ne_bytes();
1838 if cfg!(target_endian = \"big\") {
1845 #[unstable(feature = "num_as_ne_bytes", issue = "76976")]
1847 pub fn as_ne_bytes(&self) -> &[u8; mem::size_of::<Self>()] {
1848 // SAFETY: integers are plain old datatypes so we can always transmute them to
1850 unsafe { &*(self as *const Self as *const _) }
1855 concat!("Create a native endian integer value from its representation
1856 as a byte array in big endian.
1863 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
1864 assert_eq!(value, ", $swap_op, ");
1867 When starting from a slice rather than an array, fallible conversion APIs can be used:
1870 use std::convert::TryInto;
1872 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
1873 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
1875 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
1878 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
1879 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
1881 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
1882 Self::from_be(Self::from_ne_bytes(bytes))
1888 Create a native endian integer value from its representation
1889 as a byte array in little endian.
1896 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
1897 assert_eq!(value, ", $swap_op, ");
1900 When starting from a slice rather than an array, fallible conversion APIs can be used:
1903 use std::convert::TryInto;
1905 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
1906 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
1908 ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())
1911 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
1912 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
1914 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
1915 Self::from_le(Self::from_ne_bytes(bytes))
1920 concat!("Create a native endian integer value from its memory representation
1921 as a byte array in native endianness.
1923 As the target platform's native endianness is used, portable code
1924 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1925 appropriate instead.
1927 [`from_be_bytes`]: #method.from_be_bytes
1928 [`from_le_bytes`]: #method.from_le_bytes
1935 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
1940 assert_eq!(value, ", $swap_op, ");
1943 When starting from a slice rather than an array, fallible conversion APIs can be used:
1946 use std::convert::TryInto;
1948 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
1949 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
1951 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
1954 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
1955 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
1956 // SAFETY: const sound because integers are plain old datatypes so we can always
1957 // transmute to them
1958 #[rustc_allow_const_fn_unstable(const_fn_transmute)]
1960 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
1961 // SAFETY: integers are plain old datatypes so we can always transmute to them
1962 unsafe { mem::transmute(bytes) }
1967 concat!("**This method is soft-deprecated.**
1969 Although using it won’t cause compilation warning,
1970 new code should use [`", stringify!($SelfT), "::MIN", "`](#associatedconstant.MIN) instead.
1972 Returns the smallest value that can be represented by this integer type."),
1973 #[stable(feature = "rust1", since = "1.0.0")]
1976 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
1977 pub const fn min_value() -> Self { Self::MIN }
1981 concat!("**This method is soft-deprecated.**
1983 Although using it won’t cause compilation warning,
1984 new code should use [`", stringify!($SelfT), "::MAX", "`](#associatedconstant.MAX) instead.
1986 Returns the largest value that can be represented by this integer type."),
1987 #[stable(feature = "rust1", since = "1.0.0")]
1990 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
1991 pub const fn max_value() -> Self { Self::MAX }