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 $bound_condition:expr) => {
8 /// The smallest value that can be represented by this integer type.
15 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN, 0);")]
17 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
18 pub const MIN: Self = 0;
20 /// The largest value that can be represented by this integer type
21 #[doc = concat!("(2<sup>", $BITS, "</sup> − 1", $bound_condition, ")")]
28 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($MaxV), ");")]
30 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
31 pub const MAX: Self = !0;
33 /// The size of this integer type in bits.
38 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::BITS, ", stringify!($BITS), ");")]
40 #[stable(feature = "int_bits_const", since = "1.53.0")]
41 pub const BITS: u32 = $BITS;
43 /// Converts a string slice in a given base to an integer.
45 /// The string is expected to be an optional `+` sign
46 /// followed by digits.
47 /// Leading and trailing whitespace represent an error.
48 /// Digits are a subset of these characters, depending on `radix`:
56 /// This function panics if `radix` is not in the range from 2 to 36.
63 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));")]
65 #[stable(feature = "rust1", since = "1.0.0")]
66 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
67 from_str_radix(src, radix)
70 /// Returns the number of ones in the binary representation of `self`.
77 #[doc = concat!("let n = 0b01001100", stringify!($SelfT), ";")]
79 /// assert_eq!(n.count_ones(), 3);
81 #[stable(feature = "rust1", since = "1.0.0")]
82 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
83 #[doc(alias = "popcount")]
84 #[doc(alias = "popcnt")]
85 #[must_use = "this returns the result of the operation, \
86 without modifying the original"]
88 pub const fn count_ones(self) -> u32 {
89 intrinsics::ctpop(self as $ActualT) as u32
92 /// Returns the number of zeros in the binary representation of `self`.
99 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.count_zeros(), 0);")]
101 #[stable(feature = "rust1", since = "1.0.0")]
102 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
103 #[must_use = "this returns the result of the operation, \
104 without modifying the original"]
106 pub const fn count_zeros(self) -> u32 {
110 /// Returns the number of leading zeros in the binary representation of `self`.
117 #[doc = concat!("let n = ", stringify!($SelfT), "::MAX >> 2;")]
119 /// assert_eq!(n.leading_zeros(), 2);
121 #[stable(feature = "rust1", since = "1.0.0")]
122 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
123 #[must_use = "this returns the result of the operation, \
124 without modifying the original"]
126 pub const fn leading_zeros(self) -> u32 {
127 intrinsics::ctlz(self as $ActualT) as u32
130 /// Returns the number of trailing zeros in the binary representation
138 #[doc = concat!("let n = 0b0101000", stringify!($SelfT), ";")]
140 /// assert_eq!(n.trailing_zeros(), 3);
142 #[stable(feature = "rust1", since = "1.0.0")]
143 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
144 #[must_use = "this returns the result of the operation, \
145 without modifying the original"]
147 pub const fn trailing_zeros(self) -> u32 {
148 intrinsics::cttz(self) as u32
151 /// Returns the number of leading ones in the binary representation of `self`.
158 #[doc = concat!("let n = !(", stringify!($SelfT), "::MAX >> 2);")]
160 /// assert_eq!(n.leading_ones(), 2);
162 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
163 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
164 #[must_use = "this returns the result of the operation, \
165 without modifying the original"]
167 pub const fn leading_ones(self) -> u32 {
168 (!self).leading_zeros()
171 /// Returns the number of trailing ones in the binary representation
179 #[doc = concat!("let n = 0b1010111", stringify!($SelfT), ";")]
181 /// assert_eq!(n.trailing_ones(), 3);
183 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
184 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
185 #[must_use = "this returns the result of the operation, \
186 without modifying the original"]
188 pub const fn trailing_ones(self) -> u32 {
189 (!self).trailing_zeros()
192 /// Shifts the bits to the left by a specified amount, `n`,
193 /// wrapping the truncated bits to the end of the resulting integer.
195 /// Please note this isn't the same operation as the `<<` shifting operator!
202 #[doc = concat!("let n = ", $rot_op, stringify!($SelfT), ";")]
203 #[doc = concat!("let m = ", $rot_result, ";")]
205 #[doc = concat!("assert_eq!(n.rotate_left(", $rot, "), m);")]
207 #[stable(feature = "rust1", since = "1.0.0")]
208 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
209 #[must_use = "this returns the result of the operation, \
210 without modifying the original"]
212 pub const fn rotate_left(self, n: u32) -> Self {
213 intrinsics::rotate_left(self, n as $SelfT)
216 /// Shifts the bits to the right by a specified amount, `n`,
217 /// wrapping the truncated bits to the beginning of the resulting
220 /// Please note this isn't the same operation as the `>>` shifting operator!
227 #[doc = concat!("let n = ", $rot_result, stringify!($SelfT), ";")]
228 #[doc = concat!("let m = ", $rot_op, ";")]
230 #[doc = concat!("assert_eq!(n.rotate_right(", $rot, "), m);")]
232 #[stable(feature = "rust1", since = "1.0.0")]
233 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
234 #[must_use = "this returns the result of the operation, \
235 without modifying the original"]
237 pub const fn rotate_right(self, n: u32) -> Self {
238 intrinsics::rotate_right(self, n as $SelfT)
241 /// Reverses the byte order of the integer.
248 #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
249 /// let m = n.swap_bytes();
251 #[doc = concat!("assert_eq!(m, ", $swapped, ");")]
253 #[stable(feature = "rust1", since = "1.0.0")]
254 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
255 #[must_use = "this returns the result of the operation, \
256 without modifying the original"]
258 pub const fn swap_bytes(self) -> Self {
259 intrinsics::bswap(self as $ActualT) as Self
262 /// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
263 /// second least-significant bit becomes second most-significant bit, etc.
270 #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
271 /// let m = n.reverse_bits();
273 #[doc = concat!("assert_eq!(m, ", $reversed, ");")]
274 #[doc = concat!("assert_eq!(0, 0", stringify!($SelfT), ".reverse_bits());")]
276 #[stable(feature = "reverse_bits", since = "1.37.0")]
277 #[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
278 #[must_use = "this returns the result of the operation, \
279 without modifying the original"]
281 pub const fn reverse_bits(self) -> Self {
282 intrinsics::bitreverse(self as $ActualT) as Self
285 /// Converts an integer from big endian to the target's endianness.
287 /// On big endian this is a no-op. On little endian the bytes are
295 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
297 /// if cfg!(target_endian = "big") {
298 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_be(n), n)")]
300 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())")]
303 #[stable(feature = "rust1", since = "1.0.0")]
304 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
307 pub const fn from_be(x: Self) -> Self {
308 #[cfg(target_endian = "big")]
312 #[cfg(not(target_endian = "big"))]
318 /// Converts an integer from little endian to the target's endianness.
320 /// On little endian this is a no-op. On big endian the bytes are
328 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
330 /// if cfg!(target_endian = "little") {
331 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_le(n), n)")]
333 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())")]
336 #[stable(feature = "rust1", since = "1.0.0")]
337 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
340 pub const fn from_le(x: Self) -> Self {
341 #[cfg(target_endian = "little")]
345 #[cfg(not(target_endian = "little"))]
351 /// Converts `self` to big endian from the target's endianness.
353 /// On big endian this is a no-op. On little endian the bytes are
361 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
363 /// if cfg!(target_endian = "big") {
364 /// assert_eq!(n.to_be(), n)
366 /// assert_eq!(n.to_be(), n.swap_bytes())
369 #[stable(feature = "rust1", since = "1.0.0")]
370 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
371 #[must_use = "this returns the result of the operation, \
372 without modifying the original"]
374 pub const fn to_be(self) -> Self { // or not to be?
375 #[cfg(target_endian = "big")]
379 #[cfg(not(target_endian = "big"))]
385 /// Converts `self` to little endian from the target's endianness.
387 /// On little endian this is a no-op. On big endian the bytes are
395 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
397 /// if cfg!(target_endian = "little") {
398 /// assert_eq!(n.to_le(), n)
400 /// assert_eq!(n.to_le(), n.swap_bytes())
403 #[stable(feature = "rust1", since = "1.0.0")]
404 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
405 #[must_use = "this returns the result of the operation, \
406 without modifying the original"]
408 pub const fn to_le(self) -> Self {
409 #[cfg(target_endian = "little")]
413 #[cfg(not(target_endian = "little"))]
419 /// Checked integer addition. Computes `self + rhs`, returning `None`
420 /// if overflow occurred.
428 "assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(1), ",
429 "Some(", stringify!($SelfT), "::MAX - 1));"
431 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);")]
433 #[stable(feature = "rust1", since = "1.0.0")]
434 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
435 #[must_use = "this returns the result of the operation, \
436 without modifying the original"]
438 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
439 let (a, b) = self.overflowing_add(rhs);
440 if unlikely!(b) {None} else {Some(a)}
443 /// Unchecked integer addition. Computes `self + rhs`, assuming overflow
448 /// This results in undefined behavior when
449 #[doc = concat!("`self + rhs > ", stringify!($SelfT), "::MAX` or `self + rhs < ", stringify!($SelfT), "::MIN`,")]
450 /// i.e. when [`checked_add`] would return `None`.
452 #[doc = concat!("[`checked_add`]: ", stringify!($SelfT), "::checked_add")]
454 feature = "unchecked_math",
455 reason = "niche optimization path",
458 #[must_use = "this returns the result of the operation, \
459 without modifying the original"]
460 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
462 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
463 pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
464 // SAFETY: the caller must uphold the safety contract for
466 unsafe { intrinsics::unchecked_add(self, rhs) }
469 /// Checked addition with a signed integer. Computes `self + rhs`,
470 /// returning `None` if overflow occurred.
477 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_add_signed(2), Some(3));")]
478 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_add_signed(-2), None);")]
479 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add_signed(3), None);")]
481 #[stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
482 #[rustc_const_stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
483 #[must_use = "this returns the result of the operation, \
484 without modifying the original"]
486 pub const fn checked_add_signed(self, rhs: $SignedT) -> Option<Self> {
487 let (a, b) = self.overflowing_add_signed(rhs);
488 if unlikely!(b) {None} else {Some(a)}
491 /// Checked integer subtraction. Computes `self - rhs`, returning
492 /// `None` if overflow occurred.
499 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));")]
500 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);")]
502 #[stable(feature = "rust1", since = "1.0.0")]
503 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
504 #[must_use = "this returns the result of the operation, \
505 without modifying the original"]
507 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
508 let (a, b) = self.overflowing_sub(rhs);
509 if unlikely!(b) {None} else {Some(a)}
512 /// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
517 /// This results in undefined behavior when
518 #[doc = concat!("`self - rhs > ", stringify!($SelfT), "::MAX` or `self - rhs < ", stringify!($SelfT), "::MIN`,")]
519 /// i.e. when [`checked_sub`] would return `None`.
521 #[doc = concat!("[`checked_sub`]: ", stringify!($SelfT), "::checked_sub")]
523 feature = "unchecked_math",
524 reason = "niche optimization path",
527 #[must_use = "this returns the result of the operation, \
528 without modifying the original"]
529 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
531 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
532 pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
533 // SAFETY: the caller must uphold the safety contract for
535 unsafe { intrinsics::unchecked_sub(self, rhs) }
538 /// Checked integer multiplication. Computes `self * rhs`, returning
539 /// `None` if overflow occurred.
546 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));")]
547 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);")]
549 #[stable(feature = "rust1", since = "1.0.0")]
550 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
551 #[must_use = "this returns the result of the operation, \
552 without modifying the original"]
554 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
555 let (a, b) = self.overflowing_mul(rhs);
556 if unlikely!(b) {None} else {Some(a)}
559 /// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
564 /// This results in undefined behavior when
565 #[doc = concat!("`self * rhs > ", stringify!($SelfT), "::MAX` or `self * rhs < ", stringify!($SelfT), "::MIN`,")]
566 /// i.e. when [`checked_mul`] would return `None`.
568 #[doc = concat!("[`checked_mul`]: ", stringify!($SelfT), "::checked_mul")]
570 feature = "unchecked_math",
571 reason = "niche optimization path",
574 #[must_use = "this returns the result of the operation, \
575 without modifying the original"]
576 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
578 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
579 pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
580 // SAFETY: the caller must uphold the safety contract for
582 unsafe { intrinsics::unchecked_mul(self, rhs) }
585 /// Checked integer division. Computes `self / rhs`, returning `None`
593 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));")]
594 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);")]
596 #[stable(feature = "rust1", since = "1.0.0")]
597 #[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
598 #[must_use = "this returns the result of the operation, \
599 without modifying the original"]
601 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
602 if unlikely!(rhs == 0) {
605 // SAFETY: div by zero has been checked above and unsigned types have no other
606 // failure modes for division
607 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
611 /// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
619 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));")]
620 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);")]
622 #[stable(feature = "euclidean_division", since = "1.38.0")]
623 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
624 #[must_use = "this returns the result of the operation, \
625 without modifying the original"]
627 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
628 if unlikely!(rhs == 0) {
631 Some(self.div_euclid(rhs))
636 /// Checked integer remainder. Computes `self % rhs`, returning `None`
644 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));")]
645 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);")]
647 #[stable(feature = "wrapping", since = "1.7.0")]
648 #[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
649 #[must_use = "this returns the result of the operation, \
650 without modifying the original"]
652 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
653 if unlikely!(rhs == 0) {
656 // SAFETY: div by zero has been checked above and unsigned types have no other
657 // failure modes for division
658 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
662 /// Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
670 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));")]
671 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);")]
673 #[stable(feature = "euclidean_division", since = "1.38.0")]
674 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
675 #[must_use = "this returns the result of the operation, \
676 without modifying the original"]
678 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
679 if unlikely!(rhs == 0) {
682 Some(self.rem_euclid(rhs))
686 /// Returns the logarithm of the number with respect to an arbitrary base,
689 /// This method might not be optimized owing to implementation details;
690 /// `ilog2` can produce results more efficiently for base 2, and `ilog10`
691 /// can produce results more efficiently for base 10.
695 /// This function will panic if `self` is zero, or if `base` is less then 2.
700 /// #![feature(int_log)]
701 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".ilog(5), 1);")]
703 #[unstable(feature = "int_log", issue = "70887")]
704 #[must_use = "this returns the result of the operation, \
705 without modifying the original"]
708 pub const fn ilog(self, base: Self) -> u32 {
709 assert!(base >= 2, "base of integer logarithm must be at least 2");
710 self.checked_ilog(base).expect("argument of integer logarithm must be positive")
713 /// Returns the base 2 logarithm of the number, rounded down.
717 /// This function will panic if `self` is zero.
722 /// #![feature(int_log)]
723 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".ilog2(), 1);")]
725 #[unstable(feature = "int_log", issue = "70887")]
726 #[must_use = "this returns the result of the operation, \
727 without modifying the original"]
730 pub const fn ilog2(self) -> u32 {
731 self.checked_ilog2().expect("argument of integer logarithm must be positive")
734 /// Returns the base 10 logarithm of the number, rounded down.
738 /// This function will panic if `self` is zero.
743 /// #![feature(int_log)]
744 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".ilog10(), 1);")]
746 #[unstable(feature = "int_log", issue = "70887")]
747 #[must_use = "this returns the result of the operation, \
748 without modifying the original"]
751 pub const fn ilog10(self) -> u32 {
752 self.checked_ilog10().expect("argument of integer logarithm must be positive")
755 /// Returns the logarithm of the number with respect to an arbitrary base,
758 /// Returns `None` if the number is zero, or if the base is not at least 2.
760 /// This method might not be optimized owing to implementation details;
761 /// `checked_ilog2` can produce results more efficiently for base 2, and
762 /// `checked_ilog10` can produce results more efficiently for base 10.
767 /// #![feature(int_log)]
768 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_ilog(5), Some(1));")]
770 #[unstable(feature = "int_log", issue = "70887")]
771 #[must_use = "this returns the result of the operation, \
772 without modifying the original"]
774 pub const fn checked_ilog(self, base: Self) -> Option<u32> {
775 if self <= 0 || base <= 1 {
781 // Optimization for 128 bit wide integers.
782 if Self::BITS == 128 {
783 let b = Self::ilog2(self) / (Self::ilog2(base) + 1);
785 r /= base.pow(b as u32);
796 /// Returns the base 2 logarithm of the number, rounded down.
798 /// Returns `None` if the number is zero.
803 /// #![feature(int_log)]
804 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_ilog2(), Some(1));")]
806 #[unstable(feature = "int_log", issue = "70887")]
807 #[must_use = "this returns the result of the operation, \
808 without modifying the original"]
810 pub const fn checked_ilog2(self) -> Option<u32> {
811 if let Some(x) = <$NonZeroT>::new(self) {
818 /// Returns the base 10 logarithm of the number, rounded down.
820 /// Returns `None` if the number is zero.
825 /// #![feature(int_log)]
826 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_ilog10(), Some(1));")]
828 #[unstable(feature = "int_log", issue = "70887")]
829 #[must_use = "this returns the result of the operation, \
830 without modifying the original"]
832 pub const fn checked_ilog10(self) -> Option<u32> {
833 if let Some(x) = <$NonZeroT>::new(self) {
840 /// Checked negation. Computes `-self`, returning `None` unless `self ==
843 /// Note that negating any positive integer will overflow.
850 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));")]
851 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);")]
853 #[stable(feature = "wrapping", since = "1.7.0")]
854 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
855 #[must_use = "this returns the result of the operation, \
856 without modifying the original"]
858 pub const fn checked_neg(self) -> Option<Self> {
859 let (a, b) = self.overflowing_neg();
860 if unlikely!(b) {None} else {Some(a)}
863 /// Checked shift left. Computes `self << rhs`, returning `None`
864 /// if `rhs` is larger than or equal to the number of bits in `self`.
871 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));")]
872 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);")]
874 #[stable(feature = "wrapping", since = "1.7.0")]
875 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
876 #[must_use = "this returns the result of the operation, \
877 without modifying the original"]
879 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
880 let (a, b) = self.overflowing_shl(rhs);
881 if unlikely!(b) {None} else {Some(a)}
884 /// Unchecked shift left. Computes `self << rhs`, assuming that
885 /// `rhs` is less than the number of bits in `self`.
889 /// This results in undefined behavior if `rhs` is larger than
890 /// or equal to the number of bits in `self`,
891 /// i.e. when [`checked_shl`] would return `None`.
893 #[doc = concat!("[`checked_shl`]: ", stringify!($SelfT), "::checked_shl")]
895 feature = "unchecked_math",
896 reason = "niche optimization path",
899 #[must_use = "this returns the result of the operation, \
900 without modifying the original"]
901 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
903 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
904 pub const unsafe fn unchecked_shl(self, rhs: Self) -> Self {
905 // SAFETY: the caller must uphold the safety contract for
907 unsafe { intrinsics::unchecked_shl(self, rhs) }
910 /// Checked shift right. Computes `self >> rhs`, returning `None`
911 /// if `rhs` is larger than or equal to the number of bits in `self`.
918 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));")]
919 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);")]
921 #[stable(feature = "wrapping", since = "1.7.0")]
922 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
923 #[must_use = "this returns the result of the operation, \
924 without modifying the original"]
926 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
927 let (a, b) = self.overflowing_shr(rhs);
928 if unlikely!(b) {None} else {Some(a)}
931 /// Unchecked shift right. Computes `self >> rhs`, assuming that
932 /// `rhs` is less than the number of bits in `self`.
936 /// This results in undefined behavior if `rhs` is larger than
937 /// or equal to the number of bits in `self`,
938 /// i.e. when [`checked_shr`] would return `None`.
940 #[doc = concat!("[`checked_shr`]: ", stringify!($SelfT), "::checked_shr")]
942 feature = "unchecked_math",
943 reason = "niche optimization path",
946 #[must_use = "this returns the result of the operation, \
947 without modifying the original"]
948 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
950 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
951 pub const unsafe fn unchecked_shr(self, rhs: Self) -> Self {
952 // SAFETY: the caller must uphold the safety contract for
954 unsafe { intrinsics::unchecked_shr(self, rhs) }
957 /// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
958 /// overflow occurred.
965 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));")]
966 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);")]
968 #[stable(feature = "no_panic_pow", since = "1.34.0")]
969 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
970 #[must_use = "this returns the result of the operation, \
971 without modifying the original"]
973 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
978 let mut acc: Self = 1;
982 acc = try_opt!(acc.checked_mul(base));
985 base = try_opt!(base.checked_mul(base));
988 // since exp!=0, finally the exp must be 1.
989 // Deal with the final bit of the exponent separately, since
990 // squaring the base afterwards is not necessary and may cause a
991 // needless overflow.
993 acc.checked_mul(base)
996 /// Saturating integer addition. Computes `self + rhs`, saturating at
997 /// the numeric bounds instead of overflowing.
1004 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);")]
1005 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(127), ", stringify!($SelfT), "::MAX);")]
1007 #[stable(feature = "rust1", since = "1.0.0")]
1008 #[must_use = "this returns the result of the operation, \
1009 without modifying the original"]
1010 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1012 pub const fn saturating_add(self, rhs: Self) -> Self {
1013 intrinsics::saturating_add(self, rhs)
1016 /// Saturating addition with a signed integer. Computes `self + rhs`,
1017 /// saturating at the numeric bounds instead of overflowing.
1024 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_signed(2), 3);")]
1025 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_signed(-2), 0);")]
1026 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).saturating_add_signed(4), ", stringify!($SelfT), "::MAX);")]
1028 #[stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
1029 #[rustc_const_stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
1030 #[must_use = "this returns the result of the operation, \
1031 without modifying the original"]
1033 pub const fn saturating_add_signed(self, rhs: $SignedT) -> Self {
1034 let (res, overflow) = self.overflowing_add(rhs as Self);
1035 if overflow == (rhs < 0) {
1037 } else if overflow {
1044 /// Saturating integer subtraction. Computes `self - rhs`, saturating
1045 /// at the numeric bounds instead of overflowing.
1052 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);")]
1053 #[doc = concat!("assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);")]
1055 #[stable(feature = "rust1", since = "1.0.0")]
1056 #[must_use = "this returns the result of the operation, \
1057 without modifying the original"]
1058 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1060 pub const fn saturating_sub(self, rhs: Self) -> Self {
1061 intrinsics::saturating_sub(self, rhs)
1064 /// Saturating integer multiplication. Computes `self * rhs`,
1065 /// saturating at the numeric bounds instead of overflowing.
1072 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);")]
1073 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),"::MAX);")]
1075 #[stable(feature = "wrapping", since = "1.7.0")]
1076 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1077 #[must_use = "this returns the result of the operation, \
1078 without modifying the original"]
1080 pub const fn saturating_mul(self, rhs: Self) -> Self {
1081 match self.checked_mul(rhs) {
1087 /// Saturating integer division. Computes `self / rhs`, saturating at the
1088 /// numeric bounds instead of overflowing.
1095 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".saturating_div(2), 2);")]
1100 #[doc = concat!("let _ = 1", stringify!($SelfT), ".saturating_div(0);")]
1103 #[stable(feature = "saturating_div", since = "1.58.0")]
1104 #[rustc_const_stable(feature = "saturating_div", since = "1.58.0")]
1105 #[must_use = "this returns the result of the operation, \
1106 without modifying the original"]
1108 pub const fn saturating_div(self, rhs: Self) -> Self {
1109 // on unsigned types, there is no overflow in integer division
1110 self.wrapping_div(rhs)
1113 /// Saturating integer exponentiation. Computes `self.pow(exp)`,
1114 /// saturating at the numeric bounds instead of overflowing.
1121 #[doc = concat!("assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);")]
1122 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);")]
1124 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1125 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1126 #[must_use = "this returns the result of the operation, \
1127 without modifying the original"]
1129 pub const fn saturating_pow(self, exp: u32) -> Self {
1130 match self.checked_pow(exp) {
1136 /// Wrapping (modular) addition. Computes `self + rhs`,
1137 /// wrapping around at the boundary of the type.
1144 #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);")]
1145 #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);")]
1147 #[stable(feature = "rust1", since = "1.0.0")]
1148 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1149 #[must_use = "this returns the result of the operation, \
1150 without modifying the original"]
1152 pub const fn wrapping_add(self, rhs: Self) -> Self {
1153 intrinsics::wrapping_add(self, rhs)
1156 /// Wrapping (modular) addition with a signed integer. Computes
1157 /// `self + rhs`, wrapping around at the boundary of the type.
1164 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_add_signed(2), 3);")]
1165 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_add_signed(-2), ", stringify!($SelfT), "::MAX);")]
1166 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).wrapping_add_signed(4), 1);")]
1168 #[stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
1169 #[rustc_const_stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
1170 #[must_use = "this returns the result of the operation, \
1171 without modifying the original"]
1173 pub const fn wrapping_add_signed(self, rhs: $SignedT) -> Self {
1174 self.wrapping_add(rhs as Self)
1177 /// Wrapping (modular) subtraction. Computes `self - rhs`,
1178 /// wrapping around at the boundary of the type.
1185 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);")]
1186 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::MAX), 101);")]
1188 #[stable(feature = "rust1", since = "1.0.0")]
1189 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1190 #[must_use = "this returns the result of the operation, \
1191 without modifying the original"]
1193 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1194 intrinsics::wrapping_sub(self, rhs)
1197 /// Wrapping (modular) multiplication. Computes `self *
1198 /// rhs`, wrapping around at the boundary of the type.
1204 /// Please note that this example is shared between integer types.
1205 /// Which explains why `u8` is used here.
1208 /// assert_eq!(10u8.wrapping_mul(12), 120);
1209 /// assert_eq!(25u8.wrapping_mul(12), 44);
1211 #[stable(feature = "rust1", since = "1.0.0")]
1212 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1213 #[must_use = "this returns the result of the operation, \
1214 without modifying the original"]
1216 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1217 intrinsics::wrapping_mul(self, rhs)
1220 /// Wrapping (modular) division. Computes `self / rhs`.
1221 /// Wrapped division on unsigned types is just normal division.
1222 /// There's no way wrapping could ever happen.
1223 /// This function exists, so that all operations
1224 /// are accounted for in the wrapping operations.
1231 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);")]
1233 #[stable(feature = "num_wrapping", since = "1.2.0")]
1234 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1235 #[must_use = "this returns the result of the operation, \
1236 without modifying the original"]
1238 pub const fn wrapping_div(self, rhs: Self) -> Self {
1242 /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
1243 /// Wrapped division on unsigned types is just normal division.
1244 /// There's no way wrapping could ever happen.
1245 /// This function exists, so that all operations
1246 /// are accounted for in the wrapping operations.
1247 /// Since, for the positive integers, all common
1248 /// definitions of division are equal, this
1249 /// is exactly equal to `self.wrapping_div(rhs)`.
1256 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);")]
1258 #[stable(feature = "euclidean_division", since = "1.38.0")]
1259 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1260 #[must_use = "this returns the result of the operation, \
1261 without modifying the original"]
1263 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
1267 /// Wrapping (modular) remainder. Computes `self % rhs`.
1268 /// Wrapped remainder calculation on unsigned types is
1269 /// just the regular remainder calculation.
1270 /// There's no way wrapping could ever happen.
1271 /// This function exists, so that all operations
1272 /// are accounted for in the wrapping operations.
1279 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);")]
1281 #[stable(feature = "num_wrapping", since = "1.2.0")]
1282 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1283 #[must_use = "this returns the result of the operation, \
1284 without modifying the original"]
1286 pub const fn wrapping_rem(self, rhs: Self) -> Self {
1290 /// Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
1291 /// Wrapped modulo calculation on unsigned types is
1292 /// just the regular remainder calculation.
1293 /// There's no way wrapping could ever happen.
1294 /// This function exists, so that all operations
1295 /// are accounted for in the wrapping operations.
1296 /// Since, for the positive integers, all common
1297 /// definitions of division are equal, this
1298 /// is exactly equal to `self.wrapping_rem(rhs)`.
1305 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);")]
1307 #[stable(feature = "euclidean_division", since = "1.38.0")]
1308 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1309 #[must_use = "this returns the result of the operation, \
1310 without modifying the original"]
1312 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1316 /// Wrapping (modular) negation. Computes `-self`,
1317 /// wrapping around at the boundary of the type.
1319 /// Since unsigned types do not have negative equivalents
1320 /// all applications of this function will wrap (except for `-0`).
1321 /// For values smaller than the corresponding signed type's maximum
1322 /// the result is the same as casting the corresponding signed value.
1323 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
1324 /// `MAX` is the corresponding signed type's maximum.
1330 /// Please note that this example is shared between integer types.
1331 /// Which explains why `i8` is used here.
1334 /// assert_eq!(100i8.wrapping_neg(), -100);
1335 /// assert_eq!((-128i8).wrapping_neg(), -128);
1337 #[stable(feature = "num_wrapping", since = "1.2.0")]
1338 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1339 #[must_use = "this returns the result of the operation, \
1340 without modifying the original"]
1342 pub const fn wrapping_neg(self) -> Self {
1343 (0 as $SelfT).wrapping_sub(self)
1346 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1347 /// where `mask` removes any high-order bits of `rhs` that
1348 /// would cause the shift to exceed the bitwidth of the type.
1350 /// Note that this is *not* the same as a rotate-left; the
1351 /// RHS of a wrapping shift-left is restricted to the range
1352 /// of the type, rather than the bits shifted out of the LHS
1353 /// being returned to the other end. The primitive integer
1354 /// types all implement a [`rotate_left`](Self::rotate_left) function,
1355 /// which may be what you want instead.
1362 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);")]
1363 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);")]
1365 #[stable(feature = "num_wrapping", since = "1.2.0")]
1366 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1367 #[must_use = "this returns the result of the operation, \
1368 without modifying the original"]
1370 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1371 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1374 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1378 /// Panic-free bitwise shift-right; 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-right; the
1383 /// RHS of a wrapping shift-right 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_right`](Self::rotate_right) function,
1387 /// which may be what you want instead.
1394 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);")]
1395 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);")]
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_shr(self, rhs: u32) -> Self {
1403 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1406 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1410 /// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1411 /// wrapping around at the boundary of the type.
1418 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);")]
1419 /// assert_eq!(3u8.wrapping_pow(6), 217);
1421 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1422 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1423 #[must_use = "this returns the result of the operation, \
1424 without modifying the original"]
1426 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
1430 let mut base = self;
1431 let mut acc: Self = 1;
1435 acc = acc.wrapping_mul(base);
1438 base = base.wrapping_mul(base);
1441 // since exp!=0, finally the exp must be 1.
1442 // Deal with the final bit of the exponent separately, since
1443 // squaring the base afterwards is not necessary and may cause a
1444 // needless overflow.
1445 acc.wrapping_mul(base)
1448 /// Calculates `self` + `rhs`
1450 /// Returns a tuple of the addition along with a boolean indicating
1451 /// whether an arithmetic overflow would occur. If an overflow would
1452 /// have occurred then the wrapped value is returned.
1459 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));")]
1460 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));")]
1462 #[stable(feature = "wrapping", since = "1.7.0")]
1463 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1464 #[must_use = "this returns the result of the operation, \
1465 without modifying the original"]
1467 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1468 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1472 /// Calculates `self` + `rhs` + `carry` and returns a tuple containing
1473 /// the sum and the output carry.
1475 /// Performs "ternary addition" of two integer operands and a carry-in
1476 /// bit, and returns an output integer and a carry-out bit. This allows
1477 /// chaining together multiple additions to create a wider addition, and
1478 /// can be useful for bignum addition.
1480 #[doc = concat!("This can be thought of as a ", stringify!($BITS), "-bit \"full adder\", in the electronics sense.")]
1482 /// If the input carry is false, this method is equivalent to
1483 /// [`overflowing_add`](Self::overflowing_add), and the output carry is
1484 /// equal to the overflow flag. Note that although carry and overflow
1485 /// flags are similar for unsigned integers, they are different for
1486 /// signed integers.
1491 /// #![feature(bigint_helper_methods)]
1493 #[doc = concat!("// 3 MAX (a = 3 × 2^", stringify!($BITS), " + 2^", stringify!($BITS), " - 1)")]
1494 #[doc = concat!("// + 5 7 (b = 5 × 2^", stringify!($BITS), " + 7)")]
1496 #[doc = concat!("// 9 6 (sum = 9 × 2^", stringify!($BITS), " + 6)")]
1498 #[doc = concat!("let (a1, a0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (3, ", stringify!($SelfT), "::MAX);")]
1499 #[doc = concat!("let (b1, b0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (5, 7);")]
1500 /// let carry0 = false;
1502 /// let (sum0, carry1) = a0.carrying_add(b0, carry0);
1503 /// assert_eq!(carry1, true);
1504 /// let (sum1, carry2) = a1.carrying_add(b1, carry1);
1505 /// assert_eq!(carry2, false);
1507 /// assert_eq!((sum1, sum0), (9, 6));
1509 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
1510 #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")]
1511 #[must_use = "this returns the result of the operation, \
1512 without modifying the original"]
1514 pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
1515 // note: longer-term this should be done via an intrinsic, but this has been shown
1516 // to generate optimal code for now, and LLVM doesn't have an equivalent intrinsic
1517 let (a, b) = self.overflowing_add(rhs);
1518 let (c, d) = a.overflowing_add(carry as $SelfT);
1522 /// Calculates `self` + `rhs` with a signed `rhs`
1524 /// Returns a tuple of the addition along with a boolean indicating
1525 /// whether an arithmetic overflow would occur. If an overflow would
1526 /// have occurred then the wrapped value is returned.
1533 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_signed(2), (3, false));")]
1534 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_signed(-2), (", stringify!($SelfT), "::MAX, true));")]
1535 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).overflowing_add_signed(4), (1, true));")]
1537 #[stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
1538 #[rustc_const_stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
1539 #[must_use = "this returns the result of the operation, \
1540 without modifying the original"]
1542 pub const fn overflowing_add_signed(self, rhs: $SignedT) -> (Self, bool) {
1543 let (res, overflowed) = self.overflowing_add(rhs as Self);
1544 (res, overflowed ^ (rhs < 0))
1547 /// Calculates `self` - `rhs`
1549 /// Returns a tuple of the subtraction along with a boolean indicating
1550 /// whether an arithmetic overflow would occur. If an overflow would
1551 /// have occurred then the wrapped value is returned.
1558 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));")]
1559 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")]
1561 #[stable(feature = "wrapping", since = "1.7.0")]
1562 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1563 #[must_use = "this returns the result of the operation, \
1564 without modifying the original"]
1566 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1567 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1571 /// Calculates `self` − `rhs` − `borrow` and returns a tuple
1572 /// containing the difference and the output borrow.
1574 /// Performs "ternary subtraction" by subtracting both an integer
1575 /// operand and a borrow-in bit from `self`, and returns an output
1576 /// integer and a borrow-out bit. This allows chaining together multiple
1577 /// subtractions to create a wider subtraction, and can be useful for
1578 /// bignum subtraction.
1583 /// #![feature(bigint_helper_methods)]
1585 #[doc = concat!("// 9 6 (a = 9 × 2^", stringify!($BITS), " + 6)")]
1586 #[doc = concat!("// - 5 7 (b = 5 × 2^", stringify!($BITS), " + 7)")]
1588 #[doc = concat!("// 3 MAX (diff = 3 × 2^", stringify!($BITS), " + 2^", stringify!($BITS), " - 1)")]
1590 #[doc = concat!("let (a1, a0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (9, 6);")]
1591 #[doc = concat!("let (b1, b0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (5, 7);")]
1592 /// let borrow0 = false;
1594 /// let (diff0, borrow1) = a0.borrowing_sub(b0, borrow0);
1595 /// assert_eq!(borrow1, true);
1596 /// let (diff1, borrow2) = a1.borrowing_sub(b1, borrow1);
1597 /// assert_eq!(borrow2, false);
1599 #[doc = concat!("assert_eq!((diff1, diff0), (3, ", stringify!($SelfT), "::MAX));")]
1601 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
1602 #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")]
1603 #[must_use = "this returns the result of the operation, \
1604 without modifying the original"]
1606 pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
1607 // note: longer-term this should be done via an intrinsic, but this has been shown
1608 // to generate optimal code for now, and LLVM doesn't have an equivalent intrinsic
1609 let (a, b) = self.overflowing_sub(rhs);
1610 let (c, d) = a.overflowing_sub(borrow as $SelfT);
1614 /// Computes the absolute difference between `self` and `other`.
1621 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(80), 20", stringify!($SelfT), ");")]
1622 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(110), 10", stringify!($SelfT), ");")]
1624 #[stable(feature = "int_abs_diff", since = "1.60.0")]
1625 #[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
1626 #[must_use = "this returns the result of the operation, \
1627 without modifying the original"]
1629 pub const fn abs_diff(self, other: Self) -> Self {
1630 if mem::size_of::<Self>() == 1 {
1631 // Trick LLVM into generating the psadbw instruction when SSE2
1632 // is available and this function is autovectorized for u8's.
1633 (self as i32).wrapping_sub(other as i32).abs() as Self
1643 /// Calculates the multiplication of `self` and `rhs`.
1645 /// Returns a tuple of the multiplication along with a boolean
1646 /// indicating whether an arithmetic overflow would occur. If an
1647 /// overflow would have occurred then the wrapped value is returned.
1653 /// Please note that this example is shared between integer types.
1654 /// Which explains why `u32` is used here.
1657 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
1658 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
1660 #[stable(feature = "wrapping", since = "1.7.0")]
1661 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1662 #[must_use = "this returns the result of the operation, \
1663 without modifying the original"]
1665 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1666 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1670 /// Calculates the divisor when `self` is divided by `rhs`.
1672 /// Returns a tuple of the divisor along with a boolean indicating
1673 /// whether an arithmetic overflow would occur. Note that for unsigned
1674 /// integers overflow never occurs, so the second value is always
1679 /// This function will panic if `rhs` is 0.
1686 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));")]
1689 #[stable(feature = "wrapping", since = "1.7.0")]
1690 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1691 #[must_use = "this returns the result of the operation, \
1692 without modifying the original"]
1693 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1697 /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1699 /// Returns a tuple of the divisor along with a boolean indicating
1700 /// whether an arithmetic overflow would occur. Note that for unsigned
1701 /// integers overflow never occurs, so the second value is always
1703 /// Since, for the positive integers, all common
1704 /// definitions of division are equal, this
1705 /// is exactly equal to `self.overflowing_div(rhs)`.
1709 /// This function will panic if `rhs` is 0.
1716 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));")]
1719 #[stable(feature = "euclidean_division", since = "1.38.0")]
1720 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1721 #[must_use = "this returns the result of the operation, \
1722 without modifying the original"]
1723 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1727 /// Calculates the remainder when `self` is divided by `rhs`.
1729 /// Returns a tuple of the remainder after dividing along with a boolean
1730 /// indicating whether an arithmetic overflow would occur. Note that for
1731 /// unsigned integers overflow never occurs, so the second value is
1736 /// This function will panic if `rhs` is 0.
1743 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));")]
1746 #[stable(feature = "wrapping", since = "1.7.0")]
1747 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1748 #[must_use = "this returns the result of the operation, \
1749 without modifying the original"]
1750 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1754 /// Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
1756 /// Returns a tuple of the modulo after dividing along with a boolean
1757 /// indicating whether an arithmetic overflow would occur. Note that for
1758 /// unsigned integers overflow never occurs, so the second value is
1760 /// Since, for the positive integers, all common
1761 /// definitions of division are equal, this operation
1762 /// is exactly equal to `self.overflowing_rem(rhs)`.
1766 /// This function will panic if `rhs` is 0.
1773 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));")]
1776 #[stable(feature = "euclidean_division", since = "1.38.0")]
1777 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1778 #[must_use = "this returns the result of the operation, \
1779 without modifying the original"]
1780 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1784 /// Negates self in an overflowing fashion.
1786 /// Returns `!self + 1` using wrapping operations to return the value
1787 /// that represents the negation of this unsigned value. Note that for
1788 /// positive unsigned values overflow always occurs, but negating 0 does
1796 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));")]
1797 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT), ", true));")]
1800 #[stable(feature = "wrapping", since = "1.7.0")]
1801 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1802 #[must_use = "this returns the result of the operation, \
1803 without modifying the original"]
1804 pub const fn overflowing_neg(self) -> (Self, bool) {
1805 ((!self).wrapping_add(1), self != 0)
1808 /// Shifts self left by `rhs` bits.
1810 /// Returns a tuple of the shifted version of self along with a boolean
1811 /// indicating whether the shift value was larger than or equal to the
1812 /// number of bits. If the shift value is too large, then value is
1813 /// masked (N-1) where N is the number of bits, and this value is then
1814 /// used to perform the shift.
1821 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));")]
1822 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));")]
1824 #[stable(feature = "wrapping", since = "1.7.0")]
1825 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1826 #[must_use = "this returns the result of the operation, \
1827 without modifying the original"]
1829 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1830 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1833 /// Shifts self right by `rhs` bits.
1835 /// Returns a tuple of the shifted version of self along with a boolean
1836 /// indicating whether the shift value was larger than or equal to the
1837 /// number of bits. If the shift value is too large, then value is
1838 /// masked (N-1) where N is the number of bits, and this value is then
1839 /// used to perform the shift.
1846 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));")]
1847 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));")]
1849 #[stable(feature = "wrapping", since = "1.7.0")]
1850 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1851 #[must_use = "this returns the result of the operation, \
1852 without modifying the original"]
1854 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1855 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1858 /// Raises self to the power of `exp`, using exponentiation by squaring.
1860 /// Returns a tuple of the exponentiation along with a bool indicating
1861 /// whether an overflow happened.
1868 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));")]
1869 /// assert_eq!(3u8.overflowing_pow(6), (217, true));
1871 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1872 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1873 #[must_use = "this returns the result of the operation, \
1874 without modifying the original"]
1876 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1880 let mut base = self;
1881 let mut acc: Self = 1;
1882 let mut overflown = false;
1883 // Scratch space for storing results of overflowing_mul.
1888 r = acc.overflowing_mul(base);
1893 r = base.overflowing_mul(base);
1898 // since exp!=0, finally the exp must be 1.
1899 // Deal with the final bit of the exponent separately, since
1900 // squaring the base afterwards is not necessary and may cause a
1901 // needless overflow.
1902 r = acc.overflowing_mul(base);
1908 /// Raises self to the power of `exp`, using exponentiation by squaring.
1915 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".pow(5), 32);")]
1917 #[stable(feature = "rust1", since = "1.0.0")]
1918 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1919 #[must_use = "this returns the result of the operation, \
1920 without modifying the original"]
1922 #[rustc_inherit_overflow_checks]
1923 pub const fn pow(self, mut exp: u32) -> Self {
1927 let mut base = self;
1938 // since exp!=0, finally the exp must be 1.
1939 // Deal with the final bit of the exponent separately, since
1940 // squaring the base afterwards is not necessary and may cause a
1941 // needless overflow.
1945 /// Performs Euclidean division.
1947 /// Since, for the positive integers, all common
1948 /// definitions of division are equal, this
1949 /// is exactly equal to `self / rhs`.
1953 /// This function will panic if `rhs` is 0.
1960 #[doc = concat!("assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type")]
1962 #[stable(feature = "euclidean_division", since = "1.38.0")]
1963 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1964 #[must_use = "this returns the result of the operation, \
1965 without modifying the original"]
1967 #[rustc_inherit_overflow_checks]
1968 pub const fn div_euclid(self, rhs: Self) -> Self {
1973 /// Calculates the least remainder of `self (mod rhs)`.
1975 /// Since, for the positive integers, all common
1976 /// definitions of division are equal, this
1977 /// is exactly equal to `self % rhs`.
1981 /// This function will panic if `rhs` is 0.
1988 #[doc = concat!("assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type")]
1990 #[stable(feature = "euclidean_division", since = "1.38.0")]
1991 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1992 #[must_use = "this returns the result of the operation, \
1993 without modifying the original"]
1995 #[rustc_inherit_overflow_checks]
1996 pub const fn rem_euclid(self, rhs: Self) -> Self {
2000 /// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
2002 /// This is the same as performing `self / rhs` for all unsigned integers.
2006 /// This function will panic if `rhs` is zero.
2013 /// #![feature(int_roundings)]
2014 #[doc = concat!("assert_eq!(7_", stringify!($SelfT), ".div_floor(4), 1);")]
2016 #[unstable(feature = "int_roundings", issue = "88581")]
2017 #[must_use = "this returns the result of the operation, \
2018 without modifying the original"]
2020 pub const fn div_floor(self, rhs: Self) -> Self {
2024 /// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
2028 /// This function will panic if `rhs` is zero.
2030 /// ## Overflow behavior
2032 /// On overflow, this function will panic if overflow checks are enabled (default in debug
2033 /// mode) and wrap if overflow checks are disabled (default in release mode).
2040 /// #![feature(int_roundings)]
2041 #[doc = concat!("assert_eq!(7_", stringify!($SelfT), ".div_ceil(4), 2);")]
2043 #[unstable(feature = "int_roundings", issue = "88581")]
2044 #[must_use = "this returns the result of the operation, \
2045 without modifying the original"]
2047 #[rustc_inherit_overflow_checks]
2048 pub const fn div_ceil(self, rhs: Self) -> Self {
2051 if r > 0 && rhs > 0 {
2058 /// Calculates the smallest value greater than or equal to `self` that
2059 /// is a multiple of `rhs`.
2063 /// This function will panic if `rhs` is zero.
2065 /// ## Overflow behavior
2067 /// On overflow, this function will panic if overflow checks are enabled (default in debug
2068 /// mode) and wrap if overflow checks are disabled (default in release mode).
2075 /// #![feature(int_roundings)]
2076 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".next_multiple_of(8), 16);")]
2077 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".next_multiple_of(8), 24);")]
2079 #[unstable(feature = "int_roundings", issue = "88581")]
2080 #[must_use = "this returns the result of the operation, \
2081 without modifying the original"]
2083 #[rustc_inherit_overflow_checks]
2084 pub const fn next_multiple_of(self, rhs: Self) -> Self {
2087 r => self + (rhs - r)
2091 /// Calculates the smallest value greater than or equal to `self` that
2092 /// is a multiple of `rhs`. Returns `None` if `rhs` is zero or the
2093 /// operation would result in overflow.
2100 /// #![feature(int_roundings)]
2101 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(16));")]
2102 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(24));")]
2103 #[doc = concat!("assert_eq!(1_", stringify!($SelfT), ".checked_next_multiple_of(0), None);")]
2104 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_multiple_of(2), None);")]
2106 #[unstable(feature = "int_roundings", issue = "88581")]
2107 #[must_use = "this returns the result of the operation, \
2108 without modifying the original"]
2110 pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
2111 match try_opt!(self.checked_rem(rhs)) {
2113 // rhs - r cannot overflow because r is smaller than rhs
2114 r => self.checked_add(rhs - r)
2118 /// Returns `true` if and only if `self == 2^k` for some `k`.
2125 #[doc = concat!("assert!(16", stringify!($SelfT), ".is_power_of_two());")]
2126 #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_power_of_two());")]
2129 #[stable(feature = "rust1", since = "1.0.0")]
2130 #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
2132 pub const fn is_power_of_two(self) -> bool {
2133 self.count_ones() == 1
2136 // Returns one less than next power of two.
2137 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
2139 // 8u8.one_less_than_next_power_of_two() == 7
2140 // 6u8.one_less_than_next_power_of_two() == 7
2142 // This method cannot overflow, as in the `next_power_of_two`
2143 // overflow cases it instead ends up returning the maximum value
2144 // of the type, and can return 0 for 0.
2146 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2147 const fn one_less_than_next_power_of_two(self) -> Self {
2148 if self <= 1 { return 0; }
2151 // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros.
2152 // That means the shift is always in-bounds, and some processors
2153 // (such as intel pre-haswell) have more efficient ctlz
2154 // intrinsics when the argument is non-zero.
2155 let z = unsafe { intrinsics::ctlz_nonzero(p) };
2159 /// Returns the smallest power of two greater than or equal to `self`.
2161 /// When return value overflows (i.e., `self > (1 << (N-1))` for type
2162 /// `uN`), it panics in debug mode and the return value is wrapped to 0 in
2163 /// release mode (the only situation in which method can return 0).
2170 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);")]
2171 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);")]
2173 #[stable(feature = "rust1", since = "1.0.0")]
2174 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2175 #[must_use = "this returns the result of the operation, \
2176 without modifying the original"]
2178 #[rustc_inherit_overflow_checks]
2179 pub const fn next_power_of_two(self) -> Self {
2180 self.one_less_than_next_power_of_two() + 1
2183 /// Returns the smallest power of two greater than or equal to `n`. If
2184 /// the next power of two is greater than the type's maximum value,
2185 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
2192 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_next_power_of_two(), Some(2));")]
2193 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));")]
2194 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_power_of_two(), None);")]
2197 #[stable(feature = "rust1", since = "1.0.0")]
2198 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2199 #[must_use = "this returns the result of the operation, \
2200 without modifying the original"]
2201 pub const fn checked_next_power_of_two(self) -> Option<Self> {
2202 self.one_less_than_next_power_of_two().checked_add(1)
2205 /// Returns the smallest power of two greater than or equal to `n`. If
2206 /// the next power of two is greater than the type's maximum value,
2207 /// the return value is wrapped to `0`.
2214 /// #![feature(wrapping_next_power_of_two)]
2216 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);")]
2217 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);")]
2218 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_next_power_of_two(), 0);")]
2221 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
2222 reason = "needs decision on wrapping behaviour")]
2223 #[rustc_const_unstable(feature = "wrapping_next_power_of_two", issue = "32463")]
2224 #[must_use = "this returns the result of the operation, \
2225 without modifying the original"]
2226 pub const fn wrapping_next_power_of_two(self) -> Self {
2227 self.one_less_than_next_power_of_two().wrapping_add(1)
2230 /// Return the memory representation of this integer as a byte array in
2231 /// big-endian (network) byte order.
2233 #[doc = $to_xe_bytes_doc]
2238 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();")]
2239 #[doc = concat!("assert_eq!(bytes, ", $be_bytes, ");")]
2241 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2242 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2243 #[must_use = "this returns the result of the operation, \
2244 without modifying the original"]
2246 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2247 self.to_be().to_ne_bytes()
2250 /// Return the memory representation of this integer as a byte array in
2251 /// little-endian byte order.
2253 #[doc = $to_xe_bytes_doc]
2258 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();")]
2259 #[doc = concat!("assert_eq!(bytes, ", $le_bytes, ");")]
2261 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2262 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2263 #[must_use = "this returns the result of the operation, \
2264 without modifying the original"]
2266 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2267 self.to_le().to_ne_bytes()
2270 /// Return the memory representation of this integer as a byte array in
2271 /// native byte order.
2273 /// As the target platform's native endianness is used, portable code
2274 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2277 #[doc = $to_xe_bytes_doc]
2279 /// [`to_be_bytes`]: Self::to_be_bytes
2280 /// [`to_le_bytes`]: Self::to_le_bytes
2285 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();")]
2288 /// if cfg!(target_endian = "big") {
2289 #[doc = concat!(" ", $be_bytes)]
2291 #[doc = concat!(" ", $le_bytes)]
2295 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2296 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2297 #[must_use = "this returns the result of the operation, \
2298 without modifying the original"]
2299 // SAFETY: const sound because integers are plain old datatypes so we can always
2300 // transmute them to arrays of bytes
2302 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2303 // SAFETY: integers are plain old datatypes so we can always transmute them to
2305 unsafe { mem::transmute(self) }
2308 /// Create a native endian integer value from its representation
2309 /// as a byte array in big endian.
2311 #[doc = $from_xe_bytes_doc]
2316 #[doc = concat!("let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");")]
2317 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2320 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2323 #[doc = concat!("fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2324 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2326 #[doc = concat!(" ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())")]
2329 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2330 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2333 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2334 Self::from_be(Self::from_ne_bytes(bytes))
2337 /// Create a native endian integer value from its representation
2338 /// as a byte array in little endian.
2340 #[doc = $from_xe_bytes_doc]
2345 #[doc = concat!("let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");")]
2346 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2349 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2352 #[doc = concat!("fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2353 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2355 #[doc = concat!(" ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())")]
2358 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2359 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2362 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2363 Self::from_le(Self::from_ne_bytes(bytes))
2366 /// Create a native endian integer value from its memory representation
2367 /// as a byte array in native endianness.
2369 /// As the target platform's native endianness is used, portable code
2370 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2371 /// appropriate instead.
2373 /// [`from_be_bytes`]: Self::from_be_bytes
2374 /// [`from_le_bytes`]: Self::from_le_bytes
2376 #[doc = $from_xe_bytes_doc]
2381 #[doc = concat!("let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {")]
2382 #[doc = concat!(" ", $be_bytes, "")]
2384 #[doc = concat!(" ", $le_bytes, "")]
2386 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2389 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2392 #[doc = concat!("fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2393 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2395 #[doc = concat!(" ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())")]
2398 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2399 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2401 // SAFETY: const sound because integers are plain old datatypes so we can always
2402 // transmute to them
2404 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2405 // SAFETY: integers are plain old datatypes so we can always transmute to them
2406 unsafe { mem::transmute(bytes) }
2409 /// New code should prefer to use
2410 #[doc = concat!("[`", stringify!($SelfT), "::MIN", "`] instead.")]
2412 /// Returns the smallest value that can be represented by this integer type.
2413 #[stable(feature = "rust1", since = "1.0.0")]
2416 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2417 #[deprecated(since = "TBD", note = "replaced by the `MIN` associated constant on this type")]
2418 pub const fn min_value() -> Self { Self::MIN }
2420 /// New code should prefer to use
2421 #[doc = concat!("[`", stringify!($SelfT), "::MAX", "`] instead.")]
2423 /// Returns the largest value that can be represented by this integer type.
2424 #[stable(feature = "rust1", since = "1.0.0")]
2427 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2428 #[deprecated(since = "TBD", note = "replaced by the `MAX` associated constant on this type")]
2429 pub const fn max_value() -> Self { Self::MAX }