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 than 2.
700 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".ilog(5), 1);")]
702 #[stable(feature = "int_log", since = "CURRENT_RUSTC_VERSION")]
703 #[rustc_const_stable(feature = "int_log", since = "CURRENT_RUSTC_VERSION")]
704 #[rustc_allow_const_fn_unstable(const_option)]
705 #[must_use = "this returns the result of the operation, \
706 without modifying the original"]
709 pub const fn ilog(self, base: Self) -> u32 {
710 assert!(base >= 2, "base of integer logarithm must be at least 2");
711 self.checked_ilog(base).expect("argument of integer logarithm must be positive")
714 /// Returns the base 2 logarithm of the number, rounded down.
718 /// This function will panic if `self` is zero.
723 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".ilog2(), 1);")]
725 #[stable(feature = "int_log", since = "CURRENT_RUSTC_VERSION")]
726 #[rustc_const_stable(feature = "int_log", since = "CURRENT_RUSTC_VERSION")]
727 #[rustc_allow_const_fn_unstable(const_option)]
728 #[must_use = "this returns the result of the operation, \
729 without modifying the original"]
732 pub const fn ilog2(self) -> u32 {
733 self.checked_ilog2().expect("argument of integer logarithm must be positive")
736 /// Returns the base 10 logarithm of the number, rounded down.
740 /// This function will panic if `self` is zero.
745 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".ilog10(), 1);")]
747 #[stable(feature = "int_log", since = "CURRENT_RUSTC_VERSION")]
748 #[rustc_const_stable(feature = "int_log", since = "CURRENT_RUSTC_VERSION")]
749 #[rustc_allow_const_fn_unstable(const_option)]
750 #[must_use = "this returns the result of the operation, \
751 without modifying the original"]
754 pub const fn ilog10(self) -> u32 {
755 self.checked_ilog10().expect("argument of integer logarithm must be positive")
758 /// Returns the logarithm of the number with respect to an arbitrary base,
761 /// Returns `None` if the number is zero, or if the base is not at least 2.
763 /// This method might not be optimized owing to implementation details;
764 /// `checked_ilog2` can produce results more efficiently for base 2, and
765 /// `checked_ilog10` can produce results more efficiently for base 10.
770 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_ilog(5), Some(1));")]
772 #[stable(feature = "int_log", since = "CURRENT_RUSTC_VERSION")]
773 #[rustc_const_stable(feature = "int_log", since = "CURRENT_RUSTC_VERSION")]
774 #[must_use = "this returns the result of the operation, \
775 without modifying the original"]
777 pub const fn checked_ilog(self, base: Self) -> Option<u32> {
778 if self <= 0 || base <= 1 {
784 // Optimization for 128 bit wide integers.
785 if Self::BITS == 128 {
786 let b = Self::ilog2(self) / (Self::ilog2(base) + 1);
788 r /= base.pow(b as u32);
799 /// Returns the base 2 logarithm of the number, rounded down.
801 /// Returns `None` if the number is zero.
806 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_ilog2(), Some(1));")]
808 #[stable(feature = "int_log", since = "CURRENT_RUSTC_VERSION")]
809 #[rustc_const_stable(feature = "int_log", since = "CURRENT_RUSTC_VERSION")]
810 #[must_use = "this returns the result of the operation, \
811 without modifying the original"]
813 pub const fn checked_ilog2(self) -> Option<u32> {
814 if let Some(x) = <$NonZeroT>::new(self) {
821 /// Returns the base 10 logarithm of the number, rounded down.
823 /// Returns `None` if the number is zero.
828 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_ilog10(), Some(1));")]
830 #[stable(feature = "int_log", since = "CURRENT_RUSTC_VERSION")]
831 #[rustc_const_stable(feature = "int_log", since = "CURRENT_RUSTC_VERSION")]
832 #[must_use = "this returns the result of the operation, \
833 without modifying the original"]
835 pub const fn checked_ilog10(self) -> Option<u32> {
836 if let Some(x) = <$NonZeroT>::new(self) {
843 /// Checked negation. Computes `-self`, returning `None` unless `self ==
846 /// Note that negating any positive integer will overflow.
853 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));")]
854 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);")]
856 #[stable(feature = "wrapping", since = "1.7.0")]
857 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
858 #[must_use = "this returns the result of the operation, \
859 without modifying the original"]
861 pub const fn checked_neg(self) -> Option<Self> {
862 let (a, b) = self.overflowing_neg();
863 if unlikely!(b) {None} else {Some(a)}
866 /// Checked shift left. Computes `self << rhs`, returning `None`
867 /// if `rhs` is larger than or equal to the number of bits in `self`.
874 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));")]
875 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);")]
877 #[stable(feature = "wrapping", since = "1.7.0")]
878 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
879 #[must_use = "this returns the result of the operation, \
880 without modifying the original"]
882 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
883 let (a, b) = self.overflowing_shl(rhs);
884 if unlikely!(b) {None} else {Some(a)}
887 /// Unchecked shift left. Computes `self << rhs`, assuming that
888 /// `rhs` is less than the number of bits in `self`.
892 /// This results in undefined behavior if `rhs` is larger than
893 /// or equal to the number of bits in `self`,
894 /// i.e. when [`checked_shl`] would return `None`.
896 #[doc = concat!("[`checked_shl`]: ", stringify!($SelfT), "::checked_shl")]
898 feature = "unchecked_math",
899 reason = "niche optimization path",
902 #[must_use = "this returns the result of the operation, \
903 without modifying the original"]
904 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
906 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
907 pub const unsafe fn unchecked_shl(self, rhs: Self) -> Self {
908 // SAFETY: the caller must uphold the safety contract for
910 unsafe { intrinsics::unchecked_shl(self, rhs) }
913 /// Checked shift right. Computes `self >> rhs`, returning `None`
914 /// if `rhs` is larger than or equal to the number of bits in `self`.
921 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));")]
922 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);")]
924 #[stable(feature = "wrapping", since = "1.7.0")]
925 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
926 #[must_use = "this returns the result of the operation, \
927 without modifying the original"]
929 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
930 let (a, b) = self.overflowing_shr(rhs);
931 if unlikely!(b) {None} else {Some(a)}
934 /// Unchecked shift right. Computes `self >> rhs`, assuming that
935 /// `rhs` is less than the number of bits in `self`.
939 /// This results in undefined behavior if `rhs` is larger than
940 /// or equal to the number of bits in `self`,
941 /// i.e. when [`checked_shr`] would return `None`.
943 #[doc = concat!("[`checked_shr`]: ", stringify!($SelfT), "::checked_shr")]
945 feature = "unchecked_math",
946 reason = "niche optimization path",
949 #[must_use = "this returns the result of the operation, \
950 without modifying the original"]
951 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
953 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
954 pub const unsafe fn unchecked_shr(self, rhs: Self) -> Self {
955 // SAFETY: the caller must uphold the safety contract for
957 unsafe { intrinsics::unchecked_shr(self, rhs) }
960 /// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
961 /// overflow occurred.
968 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));")]
969 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);")]
971 #[stable(feature = "no_panic_pow", since = "1.34.0")]
972 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
973 #[must_use = "this returns the result of the operation, \
974 without modifying the original"]
976 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
981 let mut acc: Self = 1;
985 acc = try_opt!(acc.checked_mul(base));
988 base = try_opt!(base.checked_mul(base));
991 // since exp!=0, finally the exp must be 1.
992 // Deal with the final bit of the exponent separately, since
993 // squaring the base afterwards is not necessary and may cause a
994 // needless overflow.
996 acc.checked_mul(base)
999 /// Saturating integer addition. Computes `self + rhs`, saturating at
1000 /// the numeric bounds instead of overflowing.
1007 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);")]
1008 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(127), ", stringify!($SelfT), "::MAX);")]
1010 #[stable(feature = "rust1", since = "1.0.0")]
1011 #[must_use = "this returns the result of the operation, \
1012 without modifying the original"]
1013 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1015 pub const fn saturating_add(self, rhs: Self) -> Self {
1016 intrinsics::saturating_add(self, rhs)
1019 /// Saturating addition with a signed integer. Computes `self + rhs`,
1020 /// saturating at the numeric bounds instead of overflowing.
1027 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_signed(2), 3);")]
1028 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_signed(-2), 0);")]
1029 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).saturating_add_signed(4), ", stringify!($SelfT), "::MAX);")]
1031 #[stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
1032 #[rustc_const_stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
1033 #[must_use = "this returns the result of the operation, \
1034 without modifying the original"]
1036 pub const fn saturating_add_signed(self, rhs: $SignedT) -> Self {
1037 let (res, overflow) = self.overflowing_add(rhs as Self);
1038 if overflow == (rhs < 0) {
1040 } else if overflow {
1047 /// Saturating integer subtraction. Computes `self - rhs`, saturating
1048 /// at the numeric bounds instead of overflowing.
1055 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);")]
1056 #[doc = concat!("assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);")]
1058 #[stable(feature = "rust1", since = "1.0.0")]
1059 #[must_use = "this returns the result of the operation, \
1060 without modifying the original"]
1061 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1063 pub const fn saturating_sub(self, rhs: Self) -> Self {
1064 intrinsics::saturating_sub(self, rhs)
1067 /// Saturating integer multiplication. Computes `self * rhs`,
1068 /// saturating at the numeric bounds instead of overflowing.
1075 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);")]
1076 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),"::MAX);")]
1078 #[stable(feature = "wrapping", since = "1.7.0")]
1079 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1080 #[must_use = "this returns the result of the operation, \
1081 without modifying the original"]
1083 pub const fn saturating_mul(self, rhs: Self) -> Self {
1084 match self.checked_mul(rhs) {
1090 /// Saturating integer division. Computes `self / rhs`, saturating at the
1091 /// numeric bounds instead of overflowing.
1098 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".saturating_div(2), 2);")]
1103 #[doc = concat!("let _ = 1", stringify!($SelfT), ".saturating_div(0);")]
1106 #[stable(feature = "saturating_div", since = "1.58.0")]
1107 #[rustc_const_stable(feature = "saturating_div", since = "1.58.0")]
1108 #[must_use = "this returns the result of the operation, \
1109 without modifying the original"]
1111 pub const fn saturating_div(self, rhs: Self) -> Self {
1112 // on unsigned types, there is no overflow in integer division
1113 self.wrapping_div(rhs)
1116 /// Saturating integer exponentiation. Computes `self.pow(exp)`,
1117 /// saturating at the numeric bounds instead of overflowing.
1124 #[doc = concat!("assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);")]
1125 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);")]
1127 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1128 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1129 #[must_use = "this returns the result of the operation, \
1130 without modifying the original"]
1132 pub const fn saturating_pow(self, exp: u32) -> Self {
1133 match self.checked_pow(exp) {
1139 /// Wrapping (modular) addition. Computes `self + rhs`,
1140 /// wrapping around at the boundary of the type.
1147 #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);")]
1148 #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);")]
1150 #[stable(feature = "rust1", since = "1.0.0")]
1151 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1152 #[must_use = "this returns the result of the operation, \
1153 without modifying the original"]
1155 pub const fn wrapping_add(self, rhs: Self) -> Self {
1156 intrinsics::wrapping_add(self, rhs)
1159 /// Wrapping (modular) addition with a signed integer. Computes
1160 /// `self + rhs`, wrapping around at the boundary of the type.
1167 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_add_signed(2), 3);")]
1168 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_add_signed(-2), ", stringify!($SelfT), "::MAX);")]
1169 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).wrapping_add_signed(4), 1);")]
1171 #[stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
1172 #[rustc_const_stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
1173 #[must_use = "this returns the result of the operation, \
1174 without modifying the original"]
1176 pub const fn wrapping_add_signed(self, rhs: $SignedT) -> Self {
1177 self.wrapping_add(rhs as Self)
1180 /// Wrapping (modular) subtraction. Computes `self - rhs`,
1181 /// wrapping around at the boundary of the type.
1188 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);")]
1189 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::MAX), 101);")]
1191 #[stable(feature = "rust1", since = "1.0.0")]
1192 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1193 #[must_use = "this returns the result of the operation, \
1194 without modifying the original"]
1196 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1197 intrinsics::wrapping_sub(self, rhs)
1200 /// Wrapping (modular) multiplication. Computes `self *
1201 /// rhs`, wrapping around at the boundary of the type.
1207 /// Please note that this example is shared between integer types.
1208 /// Which explains why `u8` is used here.
1211 /// assert_eq!(10u8.wrapping_mul(12), 120);
1212 /// assert_eq!(25u8.wrapping_mul(12), 44);
1214 #[stable(feature = "rust1", since = "1.0.0")]
1215 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1216 #[must_use = "this returns the result of the operation, \
1217 without modifying the original"]
1219 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1220 intrinsics::wrapping_mul(self, rhs)
1223 /// Wrapping (modular) division. Computes `self / rhs`.
1224 /// Wrapped division on unsigned types is just normal division.
1225 /// There's no way wrapping could ever happen.
1226 /// This function exists, so that all operations
1227 /// are accounted for in the wrapping operations.
1234 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);")]
1236 #[stable(feature = "num_wrapping", since = "1.2.0")]
1237 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1238 #[must_use = "this returns the result of the operation, \
1239 without modifying the original"]
1241 pub const fn wrapping_div(self, rhs: Self) -> Self {
1245 /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
1246 /// Wrapped division on unsigned types is just normal division.
1247 /// There's no way wrapping could ever happen.
1248 /// This function exists, so that all operations
1249 /// are accounted for in the wrapping operations.
1250 /// Since, for the positive integers, all common
1251 /// definitions of division are equal, this
1252 /// is exactly equal to `self.wrapping_div(rhs)`.
1259 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);")]
1261 #[stable(feature = "euclidean_division", since = "1.38.0")]
1262 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1263 #[must_use = "this returns the result of the operation, \
1264 without modifying the original"]
1266 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
1270 /// Wrapping (modular) remainder. Computes `self % rhs`.
1271 /// Wrapped remainder calculation on unsigned types is
1272 /// just the regular remainder calculation.
1273 /// There's no way wrapping could ever happen.
1274 /// This function exists, so that all operations
1275 /// are accounted for in the wrapping operations.
1282 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);")]
1284 #[stable(feature = "num_wrapping", since = "1.2.0")]
1285 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1286 #[must_use = "this returns the result of the operation, \
1287 without modifying the original"]
1289 pub const fn wrapping_rem(self, rhs: Self) -> Self {
1293 /// Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
1294 /// Wrapped modulo calculation on unsigned types is
1295 /// just the regular remainder calculation.
1296 /// There's no way wrapping could ever happen.
1297 /// This function exists, so that all operations
1298 /// are accounted for in the wrapping operations.
1299 /// Since, for the positive integers, all common
1300 /// definitions of division are equal, this
1301 /// is exactly equal to `self.wrapping_rem(rhs)`.
1308 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);")]
1310 #[stable(feature = "euclidean_division", since = "1.38.0")]
1311 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1312 #[must_use = "this returns the result of the operation, \
1313 without modifying the original"]
1315 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1319 /// Wrapping (modular) negation. Computes `-self`,
1320 /// wrapping around at the boundary of the type.
1322 /// Since unsigned types do not have negative equivalents
1323 /// all applications of this function will wrap (except for `-0`).
1324 /// For values smaller than the corresponding signed type's maximum
1325 /// the result is the same as casting the corresponding signed value.
1326 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
1327 /// `MAX` is the corresponding signed type's maximum.
1333 /// Please note that this example is shared between integer types.
1334 /// Which explains why `i8` is used here.
1337 /// assert_eq!(100i8.wrapping_neg(), -100);
1338 /// assert_eq!((-128i8).wrapping_neg(), -128);
1340 #[stable(feature = "num_wrapping", since = "1.2.0")]
1341 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1342 #[must_use = "this returns the result of the operation, \
1343 without modifying the original"]
1345 pub const fn wrapping_neg(self) -> Self {
1346 (0 as $SelfT).wrapping_sub(self)
1349 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1350 /// where `mask` removes any high-order bits of `rhs` that
1351 /// would cause the shift to exceed the bitwidth of the type.
1353 /// Note that this is *not* the same as a rotate-left; the
1354 /// RHS of a wrapping shift-left is restricted to the range
1355 /// of the type, rather than the bits shifted out of the LHS
1356 /// being returned to the other end. The primitive integer
1357 /// types all implement a [`rotate_left`](Self::rotate_left) function,
1358 /// which may be what you want instead.
1365 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);")]
1366 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);")]
1368 #[stable(feature = "num_wrapping", since = "1.2.0")]
1369 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1370 #[must_use = "this returns the result of the operation, \
1371 without modifying the original"]
1373 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1374 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1377 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1381 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
1382 /// where `mask` removes any high-order bits of `rhs` that
1383 /// would cause the shift to exceed the bitwidth of the type.
1385 /// Note that this is *not* the same as a rotate-right; the
1386 /// RHS of a wrapping shift-right is restricted to the range
1387 /// of the type, rather than the bits shifted out of the LHS
1388 /// being returned to the other end. The primitive integer
1389 /// types all implement a [`rotate_right`](Self::rotate_right) function,
1390 /// which may be what you want instead.
1397 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);")]
1398 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);")]
1400 #[stable(feature = "num_wrapping", since = "1.2.0")]
1401 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1402 #[must_use = "this returns the result of the operation, \
1403 without modifying the original"]
1405 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1406 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1409 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1413 /// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1414 /// wrapping around at the boundary of the type.
1421 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);")]
1422 /// assert_eq!(3u8.wrapping_pow(6), 217);
1424 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1425 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1426 #[must_use = "this returns the result of the operation, \
1427 without modifying the original"]
1429 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
1433 let mut base = self;
1434 let mut acc: Self = 1;
1438 acc = acc.wrapping_mul(base);
1441 base = base.wrapping_mul(base);
1444 // since exp!=0, finally the exp must be 1.
1445 // Deal with the final bit of the exponent separately, since
1446 // squaring the base afterwards is not necessary and may cause a
1447 // needless overflow.
1448 acc.wrapping_mul(base)
1451 /// Calculates `self` + `rhs`
1453 /// Returns a tuple of the addition along with a boolean indicating
1454 /// whether an arithmetic overflow would occur. If an overflow would
1455 /// have occurred then the wrapped value is returned.
1462 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));")]
1463 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));")]
1465 #[stable(feature = "wrapping", since = "1.7.0")]
1466 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1467 #[must_use = "this returns the result of the operation, \
1468 without modifying the original"]
1470 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1471 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1475 /// Calculates `self` + `rhs` + `carry` and returns a tuple containing
1476 /// the sum and the output carry.
1478 /// Performs "ternary addition" of two integer operands and a carry-in
1479 /// bit, and returns an output integer and a carry-out bit. This allows
1480 /// chaining together multiple additions to create a wider addition, and
1481 /// can be useful for bignum addition.
1483 #[doc = concat!("This can be thought of as a ", stringify!($BITS), "-bit \"full adder\", in the electronics sense.")]
1485 /// If the input carry is false, this method is equivalent to
1486 /// [`overflowing_add`](Self::overflowing_add), and the output carry is
1487 /// equal to the overflow flag. Note that although carry and overflow
1488 /// flags are similar for unsigned integers, they are different for
1489 /// signed integers.
1494 /// #![feature(bigint_helper_methods)]
1496 #[doc = concat!("// 3 MAX (a = 3 × 2^", stringify!($BITS), " + 2^", stringify!($BITS), " - 1)")]
1497 #[doc = concat!("// + 5 7 (b = 5 × 2^", stringify!($BITS), " + 7)")]
1499 #[doc = concat!("// 9 6 (sum = 9 × 2^", stringify!($BITS), " + 6)")]
1501 #[doc = concat!("let (a1, a0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (3, ", stringify!($SelfT), "::MAX);")]
1502 #[doc = concat!("let (b1, b0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (5, 7);")]
1503 /// let carry0 = false;
1505 /// let (sum0, carry1) = a0.carrying_add(b0, carry0);
1506 /// assert_eq!(carry1, true);
1507 /// let (sum1, carry2) = a1.carrying_add(b1, carry1);
1508 /// assert_eq!(carry2, false);
1510 /// assert_eq!((sum1, sum0), (9, 6));
1512 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
1513 #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")]
1514 #[must_use = "this returns the result of the operation, \
1515 without modifying the original"]
1517 pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
1518 // note: longer-term this should be done via an intrinsic, but this has been shown
1519 // to generate optimal code for now, and LLVM doesn't have an equivalent intrinsic
1520 let (a, b) = self.overflowing_add(rhs);
1521 let (c, d) = a.overflowing_add(carry as $SelfT);
1525 /// Calculates `self` + `rhs` with a signed `rhs`
1527 /// Returns a tuple of the addition along with a boolean indicating
1528 /// whether an arithmetic overflow would occur. If an overflow would
1529 /// have occurred then the wrapped value is returned.
1536 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_signed(2), (3, false));")]
1537 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_signed(-2), (", stringify!($SelfT), "::MAX, true));")]
1538 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).overflowing_add_signed(4), (1, true));")]
1540 #[stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
1541 #[rustc_const_stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
1542 #[must_use = "this returns the result of the operation, \
1543 without modifying the original"]
1545 pub const fn overflowing_add_signed(self, rhs: $SignedT) -> (Self, bool) {
1546 let (res, overflowed) = self.overflowing_add(rhs as Self);
1547 (res, overflowed ^ (rhs < 0))
1550 /// Calculates `self` - `rhs`
1552 /// Returns a tuple of the subtraction along with a boolean indicating
1553 /// whether an arithmetic overflow would occur. If an overflow would
1554 /// have occurred then the wrapped value is returned.
1561 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));")]
1562 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")]
1564 #[stable(feature = "wrapping", since = "1.7.0")]
1565 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1566 #[must_use = "this returns the result of the operation, \
1567 without modifying the original"]
1569 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1570 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1574 /// Calculates `self` − `rhs` − `borrow` and returns a tuple
1575 /// containing the difference and the output borrow.
1577 /// Performs "ternary subtraction" by subtracting both an integer
1578 /// operand and a borrow-in bit from `self`, and returns an output
1579 /// integer and a borrow-out bit. This allows chaining together multiple
1580 /// subtractions to create a wider subtraction, and can be useful for
1581 /// bignum subtraction.
1586 /// #![feature(bigint_helper_methods)]
1588 #[doc = concat!("// 9 6 (a = 9 × 2^", stringify!($BITS), " + 6)")]
1589 #[doc = concat!("// - 5 7 (b = 5 × 2^", stringify!($BITS), " + 7)")]
1591 #[doc = concat!("// 3 MAX (diff = 3 × 2^", stringify!($BITS), " + 2^", stringify!($BITS), " - 1)")]
1593 #[doc = concat!("let (a1, a0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (9, 6);")]
1594 #[doc = concat!("let (b1, b0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (5, 7);")]
1595 /// let borrow0 = false;
1597 /// let (diff0, borrow1) = a0.borrowing_sub(b0, borrow0);
1598 /// assert_eq!(borrow1, true);
1599 /// let (diff1, borrow2) = a1.borrowing_sub(b1, borrow1);
1600 /// assert_eq!(borrow2, false);
1602 #[doc = concat!("assert_eq!((diff1, diff0), (3, ", stringify!($SelfT), "::MAX));")]
1604 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
1605 #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")]
1606 #[must_use = "this returns the result of the operation, \
1607 without modifying the original"]
1609 pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
1610 // note: longer-term this should be done via an intrinsic, but this has been shown
1611 // to generate optimal code for now, and LLVM doesn't have an equivalent intrinsic
1612 let (a, b) = self.overflowing_sub(rhs);
1613 let (c, d) = a.overflowing_sub(borrow as $SelfT);
1617 /// Computes the absolute difference between `self` and `other`.
1624 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(80), 20", stringify!($SelfT), ");")]
1625 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(110), 10", stringify!($SelfT), ");")]
1627 #[stable(feature = "int_abs_diff", since = "1.60.0")]
1628 #[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
1629 #[must_use = "this returns the result of the operation, \
1630 without modifying the original"]
1632 pub const fn abs_diff(self, other: Self) -> Self {
1633 if mem::size_of::<Self>() == 1 {
1634 // Trick LLVM into generating the psadbw instruction when SSE2
1635 // is available and this function is autovectorized for u8's.
1636 (self as i32).wrapping_sub(other as i32).abs() as Self
1646 /// Calculates the multiplication of `self` and `rhs`.
1648 /// Returns a tuple of the multiplication along with a boolean
1649 /// indicating whether an arithmetic overflow would occur. If an
1650 /// overflow would have occurred then the wrapped value is returned.
1656 /// Please note that this example is shared between integer types.
1657 /// Which explains why `u32` is used here.
1660 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
1661 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
1663 #[stable(feature = "wrapping", since = "1.7.0")]
1664 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1665 #[must_use = "this returns the result of the operation, \
1666 without modifying the original"]
1668 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1669 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1673 /// Calculates the divisor when `self` is divided by `rhs`.
1675 /// Returns a tuple of the divisor along with a boolean indicating
1676 /// whether an arithmetic overflow would occur. Note that for unsigned
1677 /// integers overflow never occurs, so the second value is always
1682 /// This function will panic if `rhs` is 0.
1689 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));")]
1692 #[stable(feature = "wrapping", since = "1.7.0")]
1693 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1694 #[must_use = "this returns the result of the operation, \
1695 without modifying the original"]
1696 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1700 /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1702 /// Returns a tuple of the divisor along with a boolean indicating
1703 /// whether an arithmetic overflow would occur. Note that for unsigned
1704 /// integers overflow never occurs, so the second value is always
1706 /// Since, for the positive integers, all common
1707 /// definitions of division are equal, this
1708 /// is exactly equal to `self.overflowing_div(rhs)`.
1712 /// This function will panic if `rhs` is 0.
1719 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));")]
1722 #[stable(feature = "euclidean_division", since = "1.38.0")]
1723 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1724 #[must_use = "this returns the result of the operation, \
1725 without modifying the original"]
1726 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1730 /// Calculates the remainder when `self` is divided by `rhs`.
1732 /// Returns a tuple of the remainder after dividing along with a boolean
1733 /// indicating whether an arithmetic overflow would occur. Note that for
1734 /// unsigned integers overflow never occurs, so the second value is
1739 /// This function will panic if `rhs` is 0.
1746 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));")]
1749 #[stable(feature = "wrapping", since = "1.7.0")]
1750 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1751 #[must_use = "this returns the result of the operation, \
1752 without modifying the original"]
1753 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1757 /// Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
1759 /// Returns a tuple of the modulo after dividing along with a boolean
1760 /// indicating whether an arithmetic overflow would occur. Note that for
1761 /// unsigned integers overflow never occurs, so the second value is
1763 /// Since, for the positive integers, all common
1764 /// definitions of division are equal, this operation
1765 /// is exactly equal to `self.overflowing_rem(rhs)`.
1769 /// This function will panic if `rhs` is 0.
1776 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));")]
1779 #[stable(feature = "euclidean_division", since = "1.38.0")]
1780 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1781 #[must_use = "this returns the result of the operation, \
1782 without modifying the original"]
1783 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1787 /// Negates self in an overflowing fashion.
1789 /// Returns `!self + 1` using wrapping operations to return the value
1790 /// that represents the negation of this unsigned value. Note that for
1791 /// positive unsigned values overflow always occurs, but negating 0 does
1799 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));")]
1800 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT), ", true));")]
1803 #[stable(feature = "wrapping", since = "1.7.0")]
1804 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1805 #[must_use = "this returns the result of the operation, \
1806 without modifying the original"]
1807 pub const fn overflowing_neg(self) -> (Self, bool) {
1808 ((!self).wrapping_add(1), self != 0)
1811 /// Shifts self left by `rhs` bits.
1813 /// Returns a tuple of the shifted version of self along with a boolean
1814 /// indicating whether the shift value was larger than or equal to the
1815 /// number of bits. If the shift value is too large, then value is
1816 /// masked (N-1) where N is the number of bits, and this value is then
1817 /// used to perform the shift.
1824 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));")]
1825 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));")]
1827 #[stable(feature = "wrapping", since = "1.7.0")]
1828 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1829 #[must_use = "this returns the result of the operation, \
1830 without modifying the original"]
1832 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1833 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1836 /// Shifts self right by `rhs` bits.
1838 /// Returns a tuple of the shifted version of self along with a boolean
1839 /// indicating whether the shift value was larger than or equal to the
1840 /// number of bits. If the shift value is too large, then value is
1841 /// masked (N-1) where N is the number of bits, and this value is then
1842 /// used to perform the shift.
1849 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));")]
1850 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));")]
1852 #[stable(feature = "wrapping", since = "1.7.0")]
1853 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1854 #[must_use = "this returns the result of the operation, \
1855 without modifying the original"]
1857 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1858 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1861 /// Raises self to the power of `exp`, using exponentiation by squaring.
1863 /// Returns a tuple of the exponentiation along with a bool indicating
1864 /// whether an overflow happened.
1871 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));")]
1872 /// assert_eq!(3u8.overflowing_pow(6), (217, true));
1874 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1875 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1876 #[must_use = "this returns the result of the operation, \
1877 without modifying the original"]
1879 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1883 let mut base = self;
1884 let mut acc: Self = 1;
1885 let mut overflown = false;
1886 // Scratch space for storing results of overflowing_mul.
1891 r = acc.overflowing_mul(base);
1896 r = base.overflowing_mul(base);
1901 // since exp!=0, finally the exp must be 1.
1902 // Deal with the final bit of the exponent separately, since
1903 // squaring the base afterwards is not necessary and may cause a
1904 // needless overflow.
1905 r = acc.overflowing_mul(base);
1911 /// Raises self to the power of `exp`, using exponentiation by squaring.
1918 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".pow(5), 32);")]
1920 #[stable(feature = "rust1", since = "1.0.0")]
1921 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1922 #[must_use = "this returns the result of the operation, \
1923 without modifying the original"]
1925 #[rustc_inherit_overflow_checks]
1926 pub const fn pow(self, mut exp: u32) -> Self {
1930 let mut base = self;
1941 // since exp!=0, finally the exp must be 1.
1942 // Deal with the final bit of the exponent separately, since
1943 // squaring the base afterwards is not necessary and may cause a
1944 // needless overflow.
1948 /// Performs Euclidean division.
1950 /// Since, for the positive integers, all common
1951 /// definitions of division are equal, this
1952 /// is exactly equal to `self / rhs`.
1956 /// This function will panic if `rhs` is 0.
1963 #[doc = concat!("assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type")]
1965 #[stable(feature = "euclidean_division", since = "1.38.0")]
1966 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1967 #[must_use = "this returns the result of the operation, \
1968 without modifying the original"]
1970 #[rustc_inherit_overflow_checks]
1971 pub const fn div_euclid(self, rhs: Self) -> Self {
1976 /// Calculates the least remainder of `self (mod rhs)`.
1978 /// Since, for the positive integers, all common
1979 /// definitions of division are equal, this
1980 /// is exactly equal to `self % rhs`.
1984 /// This function will panic if `rhs` is 0.
1991 #[doc = concat!("assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type")]
1993 #[stable(feature = "euclidean_division", since = "1.38.0")]
1994 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1995 #[must_use = "this returns the result of the operation, \
1996 without modifying the original"]
1998 #[rustc_inherit_overflow_checks]
1999 pub const fn rem_euclid(self, rhs: Self) -> Self {
2003 /// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
2005 /// This is the same as performing `self / rhs` for all unsigned integers.
2009 /// This function will panic if `rhs` is zero.
2016 /// #![feature(int_roundings)]
2017 #[doc = concat!("assert_eq!(7_", stringify!($SelfT), ".div_floor(4), 1);")]
2019 #[unstable(feature = "int_roundings", issue = "88581")]
2020 #[must_use = "this returns the result of the operation, \
2021 without modifying the original"]
2023 pub const fn div_floor(self, rhs: Self) -> Self {
2027 /// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
2031 /// This function will panic if `rhs` is zero.
2033 /// ## Overflow behavior
2035 /// On overflow, this function will panic if overflow checks are enabled (default in debug
2036 /// mode) and wrap if overflow checks are disabled (default in release mode).
2043 /// #![feature(int_roundings)]
2044 #[doc = concat!("assert_eq!(7_", stringify!($SelfT), ".div_ceil(4), 2);")]
2046 #[unstable(feature = "int_roundings", issue = "88581")]
2047 #[must_use = "this returns the result of the operation, \
2048 without modifying the original"]
2050 #[rustc_inherit_overflow_checks]
2051 pub const fn div_ceil(self, rhs: Self) -> Self {
2054 if r > 0 && rhs > 0 {
2061 /// Calculates the smallest value greater than or equal to `self` that
2062 /// is a multiple of `rhs`.
2066 /// This function will panic if `rhs` is zero.
2068 /// ## Overflow behavior
2070 /// On overflow, this function will panic if overflow checks are enabled (default in debug
2071 /// mode) and wrap if overflow checks are disabled (default in release mode).
2078 /// #![feature(int_roundings)]
2079 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".next_multiple_of(8), 16);")]
2080 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".next_multiple_of(8), 24);")]
2082 #[unstable(feature = "int_roundings", issue = "88581")]
2083 #[must_use = "this returns the result of the operation, \
2084 without modifying the original"]
2086 #[rustc_inherit_overflow_checks]
2087 pub const fn next_multiple_of(self, rhs: Self) -> Self {
2090 r => self + (rhs - r)
2094 /// Calculates the smallest value greater than or equal to `self` that
2095 /// is a multiple of `rhs`. Returns `None` if `rhs` is zero or the
2096 /// operation would result in overflow.
2103 /// #![feature(int_roundings)]
2104 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(16));")]
2105 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(24));")]
2106 #[doc = concat!("assert_eq!(1_", stringify!($SelfT), ".checked_next_multiple_of(0), None);")]
2107 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_multiple_of(2), None);")]
2109 #[unstable(feature = "int_roundings", issue = "88581")]
2110 #[must_use = "this returns the result of the operation, \
2111 without modifying the original"]
2113 pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
2114 match try_opt!(self.checked_rem(rhs)) {
2116 // rhs - r cannot overflow because r is smaller than rhs
2117 r => self.checked_add(rhs - r)
2121 /// Returns `true` if and only if `self == 2^k` for some `k`.
2128 #[doc = concat!("assert!(16", stringify!($SelfT), ".is_power_of_two());")]
2129 #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_power_of_two());")]
2132 #[stable(feature = "rust1", since = "1.0.0")]
2133 #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
2135 pub const fn is_power_of_two(self) -> bool {
2136 self.count_ones() == 1
2139 // Returns one less than next power of two.
2140 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
2142 // 8u8.one_less_than_next_power_of_two() == 7
2143 // 6u8.one_less_than_next_power_of_two() == 7
2145 // This method cannot overflow, as in the `next_power_of_two`
2146 // overflow cases it instead ends up returning the maximum value
2147 // of the type, and can return 0 for 0.
2149 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2150 const fn one_less_than_next_power_of_two(self) -> Self {
2151 if self <= 1 { return 0; }
2154 // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros.
2155 // That means the shift is always in-bounds, and some processors
2156 // (such as intel pre-haswell) have more efficient ctlz
2157 // intrinsics when the argument is non-zero.
2158 let z = unsafe { intrinsics::ctlz_nonzero(p) };
2162 /// Returns the smallest power of two greater than or equal to `self`.
2164 /// When return value overflows (i.e., `self > (1 << (N-1))` for type
2165 /// `uN`), it panics in debug mode and the return value is wrapped to 0 in
2166 /// release mode (the only situation in which method can return 0).
2173 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);")]
2174 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);")]
2176 #[stable(feature = "rust1", since = "1.0.0")]
2177 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2178 #[must_use = "this returns the result of the operation, \
2179 without modifying the original"]
2181 #[rustc_inherit_overflow_checks]
2182 pub const fn next_power_of_two(self) -> Self {
2183 self.one_less_than_next_power_of_two() + 1
2186 /// Returns the smallest power of two greater than or equal to `n`. If
2187 /// the next power of two is greater than the type's maximum value,
2188 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
2195 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_next_power_of_two(), Some(2));")]
2196 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));")]
2197 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_power_of_two(), None);")]
2200 #[stable(feature = "rust1", since = "1.0.0")]
2201 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2202 #[must_use = "this returns the result of the operation, \
2203 without modifying the original"]
2204 pub const fn checked_next_power_of_two(self) -> Option<Self> {
2205 self.one_less_than_next_power_of_two().checked_add(1)
2208 /// Returns the smallest power of two greater than or equal to `n`. If
2209 /// the next power of two is greater than the type's maximum value,
2210 /// the return value is wrapped to `0`.
2217 /// #![feature(wrapping_next_power_of_two)]
2219 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);")]
2220 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);")]
2221 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_next_power_of_two(), 0);")]
2224 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
2225 reason = "needs decision on wrapping behaviour")]
2226 #[rustc_const_unstable(feature = "wrapping_next_power_of_two", issue = "32463")]
2227 #[must_use = "this returns the result of the operation, \
2228 without modifying the original"]
2229 pub const fn wrapping_next_power_of_two(self) -> Self {
2230 self.one_less_than_next_power_of_two().wrapping_add(1)
2233 /// Return the memory representation of this integer as a byte array in
2234 /// big-endian (network) byte order.
2236 #[doc = $to_xe_bytes_doc]
2241 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();")]
2242 #[doc = concat!("assert_eq!(bytes, ", $be_bytes, ");")]
2244 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2245 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2246 #[must_use = "this returns the result of the operation, \
2247 without modifying the original"]
2249 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2250 self.to_be().to_ne_bytes()
2253 /// Return the memory representation of this integer as a byte array in
2254 /// little-endian byte order.
2256 #[doc = $to_xe_bytes_doc]
2261 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();")]
2262 #[doc = concat!("assert_eq!(bytes, ", $le_bytes, ");")]
2264 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2265 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2266 #[must_use = "this returns the result of the operation, \
2267 without modifying the original"]
2269 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2270 self.to_le().to_ne_bytes()
2273 /// Return the memory representation of this integer as a byte array in
2274 /// native byte order.
2276 /// As the target platform's native endianness is used, portable code
2277 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2280 #[doc = $to_xe_bytes_doc]
2282 /// [`to_be_bytes`]: Self::to_be_bytes
2283 /// [`to_le_bytes`]: Self::to_le_bytes
2288 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();")]
2291 /// if cfg!(target_endian = "big") {
2292 #[doc = concat!(" ", $be_bytes)]
2294 #[doc = concat!(" ", $le_bytes)]
2298 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2299 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2300 #[must_use = "this returns the result of the operation, \
2301 without modifying the original"]
2302 // SAFETY: const sound because integers are plain old datatypes so we can always
2303 // transmute them to arrays of bytes
2305 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2306 // SAFETY: integers are plain old datatypes so we can always transmute them to
2308 unsafe { mem::transmute(self) }
2311 /// Create a native endian integer value from its representation
2312 /// as a byte array in big endian.
2314 #[doc = $from_xe_bytes_doc]
2319 #[doc = concat!("let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");")]
2320 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2323 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2326 #[doc = concat!("fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2327 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2329 #[doc = concat!(" ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())")]
2332 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2333 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2336 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2337 Self::from_be(Self::from_ne_bytes(bytes))
2340 /// Create a native endian integer value from its representation
2341 /// as a byte array in little endian.
2343 #[doc = $from_xe_bytes_doc]
2348 #[doc = concat!("let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");")]
2349 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2352 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2355 #[doc = concat!("fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2356 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2358 #[doc = concat!(" ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())")]
2361 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2362 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2365 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2366 Self::from_le(Self::from_ne_bytes(bytes))
2369 /// Create a native endian integer value from its memory representation
2370 /// as a byte array in native endianness.
2372 /// As the target platform's native endianness is used, portable code
2373 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2374 /// appropriate instead.
2376 /// [`from_be_bytes`]: Self::from_be_bytes
2377 /// [`from_le_bytes`]: Self::from_le_bytes
2379 #[doc = $from_xe_bytes_doc]
2384 #[doc = concat!("let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {")]
2385 #[doc = concat!(" ", $be_bytes, "")]
2387 #[doc = concat!(" ", $le_bytes, "")]
2389 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2392 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2395 #[doc = concat!("fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2396 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2398 #[doc = concat!(" ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())")]
2401 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2402 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2404 // SAFETY: const sound because integers are plain old datatypes so we can always
2405 // transmute to them
2407 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2408 // SAFETY: integers are plain old datatypes so we can always transmute to them
2409 unsafe { mem::transmute(bytes) }
2412 /// New code should prefer to use
2413 #[doc = concat!("[`", stringify!($SelfT), "::MIN", "`] instead.")]
2415 /// Returns the smallest value that can be represented by this integer type.
2416 #[stable(feature = "rust1", since = "1.0.0")]
2419 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2420 #[deprecated(since = "TBD", note = "replaced by the `MIN` associated constant on this type")]
2421 pub const fn min_value() -> Self { Self::MIN }
2423 /// New code should prefer to use
2424 #[doc = concat!("[`", stringify!($SelfT), "::MAX", "`] instead.")]
2426 /// Returns the largest value that can be represented by this integer type.
2427 #[stable(feature = "rust1", since = "1.0.0")]
2430 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2431 #[deprecated(since = "TBD", note = "replaced by the `MAX` associated constant on this type")]
2432 pub const fn max_value() -> Self { Self::MAX }