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`.
112 /// Depending on what you're doing with the value, you might also be interested in the
113 /// [`ilog2`] function which returns a consistent number, even if the type widens.
120 #[doc = concat!("let n = ", stringify!($SelfT), "::MAX >> 2;")]
122 /// assert_eq!(n.leading_zeros(), 2);
124 #[doc = concat!("[`ilog2`]: ", stringify!($SelfT), "::ilog2")]
125 #[stable(feature = "rust1", since = "1.0.0")]
126 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
127 #[must_use = "this returns the result of the operation, \
128 without modifying the original"]
130 pub const fn leading_zeros(self) -> u32 {
131 intrinsics::ctlz(self as $ActualT) as u32
134 /// Returns the number of trailing zeros in the binary representation
142 #[doc = concat!("let n = 0b0101000", stringify!($SelfT), ";")]
144 /// assert_eq!(n.trailing_zeros(), 3);
146 #[stable(feature = "rust1", since = "1.0.0")]
147 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
148 #[must_use = "this returns the result of the operation, \
149 without modifying the original"]
151 pub const fn trailing_zeros(self) -> u32 {
152 intrinsics::cttz(self) as u32
155 /// Returns the number of leading ones in the binary representation of `self`.
162 #[doc = concat!("let n = !(", stringify!($SelfT), "::MAX >> 2);")]
164 /// assert_eq!(n.leading_ones(), 2);
166 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
167 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
168 #[must_use = "this returns the result of the operation, \
169 without modifying the original"]
171 pub const fn leading_ones(self) -> u32 {
172 (!self).leading_zeros()
175 /// Returns the number of trailing ones in the binary representation
183 #[doc = concat!("let n = 0b1010111", stringify!($SelfT), ";")]
185 /// assert_eq!(n.trailing_ones(), 3);
187 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
188 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
189 #[must_use = "this returns the result of the operation, \
190 without modifying the original"]
192 pub const fn trailing_ones(self) -> u32 {
193 (!self).trailing_zeros()
196 /// Shifts the bits to the left by a specified amount, `n`,
197 /// wrapping the truncated bits to the end of the resulting integer.
199 /// Please note this isn't the same operation as the `<<` shifting operator!
206 #[doc = concat!("let n = ", $rot_op, stringify!($SelfT), ";")]
207 #[doc = concat!("let m = ", $rot_result, ";")]
209 #[doc = concat!("assert_eq!(n.rotate_left(", $rot, "), m);")]
211 #[stable(feature = "rust1", since = "1.0.0")]
212 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
213 #[must_use = "this returns the result of the operation, \
214 without modifying the original"]
216 pub const fn rotate_left(self, n: u32) -> Self {
217 intrinsics::rotate_left(self, n as $SelfT)
220 /// Shifts the bits to the right by a specified amount, `n`,
221 /// wrapping the truncated bits to the beginning of the resulting
224 /// Please note this isn't the same operation as the `>>` shifting operator!
231 #[doc = concat!("let n = ", $rot_result, stringify!($SelfT), ";")]
232 #[doc = concat!("let m = ", $rot_op, ";")]
234 #[doc = concat!("assert_eq!(n.rotate_right(", $rot, "), m);")]
236 #[stable(feature = "rust1", since = "1.0.0")]
237 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
238 #[must_use = "this returns the result of the operation, \
239 without modifying the original"]
241 pub const fn rotate_right(self, n: u32) -> Self {
242 intrinsics::rotate_right(self, n as $SelfT)
245 /// Reverses the byte order of the integer.
252 #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
253 /// let m = n.swap_bytes();
255 #[doc = concat!("assert_eq!(m, ", $swapped, ");")]
257 #[stable(feature = "rust1", since = "1.0.0")]
258 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
259 #[must_use = "this returns the result of the operation, \
260 without modifying the original"]
262 pub const fn swap_bytes(self) -> Self {
263 intrinsics::bswap(self as $ActualT) as Self
266 /// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
267 /// second least-significant bit becomes second most-significant bit, etc.
274 #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
275 /// let m = n.reverse_bits();
277 #[doc = concat!("assert_eq!(m, ", $reversed, ");")]
278 #[doc = concat!("assert_eq!(0, 0", stringify!($SelfT), ".reverse_bits());")]
280 #[stable(feature = "reverse_bits", since = "1.37.0")]
281 #[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
282 #[must_use = "this returns the result of the operation, \
283 without modifying the original"]
285 pub const fn reverse_bits(self) -> Self {
286 intrinsics::bitreverse(self as $ActualT) as Self
289 /// Converts an integer from big endian to the target's endianness.
291 /// On big endian this is a no-op. On little endian the bytes are
299 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
301 /// if cfg!(target_endian = "big") {
302 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_be(n), n)")]
304 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())")]
307 #[stable(feature = "rust1", since = "1.0.0")]
308 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
311 pub const fn from_be(x: Self) -> Self {
312 #[cfg(target_endian = "big")]
316 #[cfg(not(target_endian = "big"))]
322 /// Converts an integer from little endian to the target's endianness.
324 /// On little endian this is a no-op. On big endian the bytes are
332 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
334 /// if cfg!(target_endian = "little") {
335 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_le(n), n)")]
337 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())")]
340 #[stable(feature = "rust1", since = "1.0.0")]
341 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
344 pub const fn from_le(x: Self) -> Self {
345 #[cfg(target_endian = "little")]
349 #[cfg(not(target_endian = "little"))]
355 /// Converts `self` to big endian from the target's endianness.
357 /// On big endian this is a no-op. On little endian the bytes are
365 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
367 /// if cfg!(target_endian = "big") {
368 /// assert_eq!(n.to_be(), n)
370 /// assert_eq!(n.to_be(), n.swap_bytes())
373 #[stable(feature = "rust1", since = "1.0.0")]
374 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
375 #[must_use = "this returns the result of the operation, \
376 without modifying the original"]
378 pub const fn to_be(self) -> Self { // or not to be?
379 #[cfg(target_endian = "big")]
383 #[cfg(not(target_endian = "big"))]
389 /// Converts `self` to little endian from the target's endianness.
391 /// On little endian this is a no-op. On big endian the bytes are
399 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
401 /// if cfg!(target_endian = "little") {
402 /// assert_eq!(n.to_le(), n)
404 /// assert_eq!(n.to_le(), n.swap_bytes())
407 #[stable(feature = "rust1", since = "1.0.0")]
408 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
409 #[must_use = "this returns the result of the operation, \
410 without modifying the original"]
412 pub const fn to_le(self) -> Self {
413 #[cfg(target_endian = "little")]
417 #[cfg(not(target_endian = "little"))]
423 /// Checked integer addition. Computes `self + rhs`, returning `None`
424 /// if overflow occurred.
432 "assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(1), ",
433 "Some(", stringify!($SelfT), "::MAX - 1));"
435 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);")]
437 #[stable(feature = "rust1", since = "1.0.0")]
438 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
439 #[must_use = "this returns the result of the operation, \
440 without modifying the original"]
442 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
443 let (a, b) = self.overflowing_add(rhs);
444 if unlikely!(b) {None} else {Some(a)}
447 /// Unchecked integer addition. Computes `self + rhs`, assuming overflow
452 /// This results in undefined behavior when
453 #[doc = concat!("`self + rhs > ", stringify!($SelfT), "::MAX` or `self + rhs < ", stringify!($SelfT), "::MIN`,")]
454 /// i.e. when [`checked_add`] would return `None`.
456 #[doc = concat!("[`checked_add`]: ", stringify!($SelfT), "::checked_add")]
458 feature = "unchecked_math",
459 reason = "niche optimization path",
462 #[must_use = "this returns the result of the operation, \
463 without modifying the original"]
464 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
466 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
467 pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
468 // SAFETY: the caller must uphold the safety contract for
470 unsafe { intrinsics::unchecked_add(self, rhs) }
473 /// Checked addition with a signed integer. Computes `self + rhs`,
474 /// returning `None` if overflow occurred.
481 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_add_signed(2), Some(3));")]
482 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_add_signed(-2), None);")]
483 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add_signed(3), None);")]
485 #[stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
486 #[rustc_const_stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
487 #[must_use = "this returns the result of the operation, \
488 without modifying the original"]
490 pub const fn checked_add_signed(self, rhs: $SignedT) -> Option<Self> {
491 let (a, b) = self.overflowing_add_signed(rhs);
492 if unlikely!(b) {None} else {Some(a)}
495 /// Checked integer subtraction. Computes `self - rhs`, returning
496 /// `None` if overflow occurred.
503 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));")]
504 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);")]
506 #[stable(feature = "rust1", since = "1.0.0")]
507 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
508 #[must_use = "this returns the result of the operation, \
509 without modifying the original"]
511 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
512 let (a, b) = self.overflowing_sub(rhs);
513 if unlikely!(b) {None} else {Some(a)}
516 /// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
521 /// This results in undefined behavior when
522 #[doc = concat!("`self - rhs > ", stringify!($SelfT), "::MAX` or `self - rhs < ", stringify!($SelfT), "::MIN`,")]
523 /// i.e. when [`checked_sub`] would return `None`.
525 #[doc = concat!("[`checked_sub`]: ", stringify!($SelfT), "::checked_sub")]
527 feature = "unchecked_math",
528 reason = "niche optimization path",
531 #[must_use = "this returns the result of the operation, \
532 without modifying the original"]
533 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
535 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
536 pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
537 // SAFETY: the caller must uphold the safety contract for
539 unsafe { intrinsics::unchecked_sub(self, rhs) }
542 /// Checked integer multiplication. Computes `self * rhs`, returning
543 /// `None` if overflow occurred.
550 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));")]
551 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);")]
553 #[stable(feature = "rust1", since = "1.0.0")]
554 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
555 #[must_use = "this returns the result of the operation, \
556 without modifying the original"]
558 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
559 let (a, b) = self.overflowing_mul(rhs);
560 if unlikely!(b) {None} else {Some(a)}
563 /// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
568 /// This results in undefined behavior when
569 #[doc = concat!("`self * rhs > ", stringify!($SelfT), "::MAX` or `self * rhs < ", stringify!($SelfT), "::MIN`,")]
570 /// i.e. when [`checked_mul`] would return `None`.
572 #[doc = concat!("[`checked_mul`]: ", stringify!($SelfT), "::checked_mul")]
574 feature = "unchecked_math",
575 reason = "niche optimization path",
578 #[must_use = "this returns the result of the operation, \
579 without modifying the original"]
580 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
582 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
583 pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
584 // SAFETY: the caller must uphold the safety contract for
586 unsafe { intrinsics::unchecked_mul(self, rhs) }
589 /// Checked integer division. Computes `self / rhs`, returning `None`
597 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));")]
598 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);")]
600 #[stable(feature = "rust1", since = "1.0.0")]
601 #[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
602 #[must_use = "this returns the result of the operation, \
603 without modifying the original"]
605 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
606 if unlikely!(rhs == 0) {
609 // SAFETY: div by zero has been checked above and unsigned types have no other
610 // failure modes for division
611 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
615 /// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
623 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));")]
624 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);")]
626 #[stable(feature = "euclidean_division", since = "1.38.0")]
627 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
628 #[must_use = "this returns the result of the operation, \
629 without modifying the original"]
631 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
632 if unlikely!(rhs == 0) {
635 Some(self.div_euclid(rhs))
640 /// Checked integer remainder. Computes `self % rhs`, returning `None`
648 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));")]
649 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);")]
651 #[stable(feature = "wrapping", since = "1.7.0")]
652 #[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
653 #[must_use = "this returns the result of the operation, \
654 without modifying the original"]
656 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
657 if unlikely!(rhs == 0) {
660 // SAFETY: div by zero has been checked above and unsigned types have no other
661 // failure modes for division
662 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
666 /// Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
674 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));")]
675 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);")]
677 #[stable(feature = "euclidean_division", since = "1.38.0")]
678 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
679 #[must_use = "this returns the result of the operation, \
680 without modifying the original"]
682 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
683 if unlikely!(rhs == 0) {
686 Some(self.rem_euclid(rhs))
690 /// Returns the logarithm of the number with respect to an arbitrary base,
693 /// This method might not be optimized owing to implementation details;
694 /// `ilog2` can produce results more efficiently for base 2, and `ilog10`
695 /// can produce results more efficiently for base 10.
699 /// This function will panic if `self` is zero, or if `base` is less than 2.
704 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".ilog(5), 1);")]
706 #[stable(feature = "int_log", since = "CURRENT_RUSTC_VERSION")]
707 #[rustc_const_stable(feature = "int_log", since = "CURRENT_RUSTC_VERSION")]
708 #[rustc_allow_const_fn_unstable(const_option)]
709 #[must_use = "this returns the result of the operation, \
710 without modifying the original"]
713 pub const fn ilog(self, base: Self) -> u32 {
714 assert!(base >= 2, "base of integer logarithm must be at least 2");
715 self.checked_ilog(base).expect("argument of integer logarithm must be positive")
718 /// Returns the base 2 logarithm of the number, rounded down.
722 /// This function will panic if `self` is zero.
727 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".ilog2(), 1);")]
729 #[stable(feature = "int_log", since = "CURRENT_RUSTC_VERSION")]
730 #[rustc_const_stable(feature = "int_log", since = "CURRENT_RUSTC_VERSION")]
731 #[rustc_allow_const_fn_unstable(const_option)]
732 #[must_use = "this returns the result of the operation, \
733 without modifying the original"]
736 pub const fn ilog2(self) -> u32 {
737 self.checked_ilog2().expect("argument of integer logarithm must be positive")
740 /// Returns the base 10 logarithm of the number, rounded down.
744 /// This function will panic if `self` is zero.
749 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".ilog10(), 1);")]
751 #[stable(feature = "int_log", since = "CURRENT_RUSTC_VERSION")]
752 #[rustc_const_stable(feature = "int_log", since = "CURRENT_RUSTC_VERSION")]
753 #[rustc_allow_const_fn_unstable(const_option)]
754 #[must_use = "this returns the result of the operation, \
755 without modifying the original"]
758 pub const fn ilog10(self) -> u32 {
759 self.checked_ilog10().expect("argument of integer logarithm must be positive")
762 /// Returns the logarithm of the number with respect to an arbitrary base,
765 /// Returns `None` if the number is zero, or if the base is not at least 2.
767 /// This method might not be optimized owing to implementation details;
768 /// `checked_ilog2` can produce results more efficiently for base 2, and
769 /// `checked_ilog10` can produce results more efficiently for base 10.
774 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_ilog(5), Some(1));")]
776 #[stable(feature = "int_log", since = "CURRENT_RUSTC_VERSION")]
777 #[rustc_const_stable(feature = "int_log", since = "CURRENT_RUSTC_VERSION")]
778 #[must_use = "this returns the result of the operation, \
779 without modifying the original"]
781 pub const fn checked_ilog(self, base: Self) -> Option<u32> {
782 if self <= 0 || base <= 1 {
788 // Optimization for 128 bit wide integers.
789 if Self::BITS == 128 {
790 let b = Self::ilog2(self) / (Self::ilog2(base) + 1);
792 r /= base.pow(b as u32);
803 /// Returns the base 2 logarithm of the number, rounded down.
805 /// Returns `None` if the number is zero.
810 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_ilog2(), Some(1));")]
812 #[stable(feature = "int_log", since = "CURRENT_RUSTC_VERSION")]
813 #[rustc_const_stable(feature = "int_log", since = "CURRENT_RUSTC_VERSION")]
814 #[must_use = "this returns the result of the operation, \
815 without modifying the original"]
817 pub const fn checked_ilog2(self) -> Option<u32> {
818 if let Some(x) = <$NonZeroT>::new(self) {
825 /// Returns the base 10 logarithm of the number, rounded down.
827 /// Returns `None` if the number is zero.
832 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_ilog10(), Some(1));")]
834 #[stable(feature = "int_log", since = "CURRENT_RUSTC_VERSION")]
835 #[rustc_const_stable(feature = "int_log", since = "CURRENT_RUSTC_VERSION")]
836 #[must_use = "this returns the result of the operation, \
837 without modifying the original"]
839 pub const fn checked_ilog10(self) -> Option<u32> {
840 if let Some(x) = <$NonZeroT>::new(self) {
847 /// Checked negation. Computes `-self`, returning `None` unless `self ==
850 /// Note that negating any positive integer will overflow.
857 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));")]
858 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);")]
860 #[stable(feature = "wrapping", since = "1.7.0")]
861 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
862 #[must_use = "this returns the result of the operation, \
863 without modifying the original"]
865 pub const fn checked_neg(self) -> Option<Self> {
866 let (a, b) = self.overflowing_neg();
867 if unlikely!(b) {None} else {Some(a)}
870 /// Checked shift left. Computes `self << rhs`, returning `None`
871 /// if `rhs` is larger than or equal to the number of bits in `self`.
878 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));")]
879 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);")]
881 #[stable(feature = "wrapping", since = "1.7.0")]
882 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
883 #[must_use = "this returns the result of the operation, \
884 without modifying the original"]
886 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
887 let (a, b) = self.overflowing_shl(rhs);
888 if unlikely!(b) {None} else {Some(a)}
891 /// Unchecked shift left. Computes `self << rhs`, assuming that
892 /// `rhs` is less than the number of bits in `self`.
896 /// This results in undefined behavior if `rhs` is larger than
897 /// or equal to the number of bits in `self`,
898 /// i.e. when [`checked_shl`] would return `None`.
900 #[doc = concat!("[`checked_shl`]: ", stringify!($SelfT), "::checked_shl")]
902 feature = "unchecked_math",
903 reason = "niche optimization path",
906 #[must_use = "this returns the result of the operation, \
907 without modifying the original"]
908 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
910 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
911 pub const unsafe fn unchecked_shl(self, rhs: Self) -> Self {
912 // SAFETY: the caller must uphold the safety contract for
914 unsafe { intrinsics::unchecked_shl(self, rhs) }
917 /// Checked shift right. Computes `self >> rhs`, returning `None`
918 /// if `rhs` is larger than or equal to the number of bits in `self`.
925 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));")]
926 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);")]
928 #[stable(feature = "wrapping", since = "1.7.0")]
929 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
930 #[must_use = "this returns the result of the operation, \
931 without modifying the original"]
933 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
934 let (a, b) = self.overflowing_shr(rhs);
935 if unlikely!(b) {None} else {Some(a)}
938 /// Unchecked shift right. Computes `self >> rhs`, assuming that
939 /// `rhs` is less than the number of bits in `self`.
943 /// This results in undefined behavior if `rhs` is larger than
944 /// or equal to the number of bits in `self`,
945 /// i.e. when [`checked_shr`] would return `None`.
947 #[doc = concat!("[`checked_shr`]: ", stringify!($SelfT), "::checked_shr")]
949 feature = "unchecked_math",
950 reason = "niche optimization path",
953 #[must_use = "this returns the result of the operation, \
954 without modifying the original"]
955 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
957 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
958 pub const unsafe fn unchecked_shr(self, rhs: Self) -> Self {
959 // SAFETY: the caller must uphold the safety contract for
961 unsafe { intrinsics::unchecked_shr(self, rhs) }
964 /// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
965 /// overflow occurred.
972 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));")]
973 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);")]
975 #[stable(feature = "no_panic_pow", since = "1.34.0")]
976 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
977 #[must_use = "this returns the result of the operation, \
978 without modifying the original"]
980 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
985 let mut acc: Self = 1;
989 acc = try_opt!(acc.checked_mul(base));
992 base = try_opt!(base.checked_mul(base));
995 // since exp!=0, finally the exp must be 1.
996 // Deal with the final bit of the exponent separately, since
997 // squaring the base afterwards is not necessary and may cause a
998 // needless overflow.
1000 acc.checked_mul(base)
1003 /// Saturating integer addition. Computes `self + rhs`, saturating at
1004 /// the numeric bounds instead of overflowing.
1011 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);")]
1012 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(127), ", stringify!($SelfT), "::MAX);")]
1014 #[stable(feature = "rust1", since = "1.0.0")]
1015 #[must_use = "this returns the result of the operation, \
1016 without modifying the original"]
1017 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1019 pub const fn saturating_add(self, rhs: Self) -> Self {
1020 intrinsics::saturating_add(self, rhs)
1023 /// Saturating addition with a signed integer. Computes `self + rhs`,
1024 /// saturating at the numeric bounds instead of overflowing.
1031 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_signed(2), 3);")]
1032 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_signed(-2), 0);")]
1033 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).saturating_add_signed(4), ", stringify!($SelfT), "::MAX);")]
1035 #[stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
1036 #[rustc_const_stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
1037 #[must_use = "this returns the result of the operation, \
1038 without modifying the original"]
1040 pub const fn saturating_add_signed(self, rhs: $SignedT) -> Self {
1041 let (res, overflow) = self.overflowing_add(rhs as Self);
1042 if overflow == (rhs < 0) {
1044 } else if overflow {
1051 /// Saturating integer subtraction. Computes `self - rhs`, saturating
1052 /// at the numeric bounds instead of overflowing.
1059 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);")]
1060 #[doc = concat!("assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);")]
1062 #[stable(feature = "rust1", since = "1.0.0")]
1063 #[must_use = "this returns the result of the operation, \
1064 without modifying the original"]
1065 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1067 pub const fn saturating_sub(self, rhs: Self) -> Self {
1068 intrinsics::saturating_sub(self, rhs)
1071 /// Saturating integer multiplication. Computes `self * rhs`,
1072 /// saturating at the numeric bounds instead of overflowing.
1079 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);")]
1080 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),"::MAX);")]
1082 #[stable(feature = "wrapping", since = "1.7.0")]
1083 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1084 #[must_use = "this returns the result of the operation, \
1085 without modifying the original"]
1087 pub const fn saturating_mul(self, rhs: Self) -> Self {
1088 match self.checked_mul(rhs) {
1094 /// Saturating integer division. Computes `self / rhs`, saturating at the
1095 /// numeric bounds instead of overflowing.
1102 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".saturating_div(2), 2);")]
1107 #[doc = concat!("let _ = 1", stringify!($SelfT), ".saturating_div(0);")]
1110 #[stable(feature = "saturating_div", since = "1.58.0")]
1111 #[rustc_const_stable(feature = "saturating_div", since = "1.58.0")]
1112 #[must_use = "this returns the result of the operation, \
1113 without modifying the original"]
1115 pub const fn saturating_div(self, rhs: Self) -> Self {
1116 // on unsigned types, there is no overflow in integer division
1117 self.wrapping_div(rhs)
1120 /// Saturating integer exponentiation. Computes `self.pow(exp)`,
1121 /// saturating at the numeric bounds instead of overflowing.
1128 #[doc = concat!("assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);")]
1129 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);")]
1131 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1132 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1133 #[must_use = "this returns the result of the operation, \
1134 without modifying the original"]
1136 pub const fn saturating_pow(self, exp: u32) -> Self {
1137 match self.checked_pow(exp) {
1143 /// Wrapping (modular) addition. Computes `self + rhs`,
1144 /// wrapping around at the boundary of the type.
1151 #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);")]
1152 #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);")]
1154 #[stable(feature = "rust1", since = "1.0.0")]
1155 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1156 #[must_use = "this returns the result of the operation, \
1157 without modifying the original"]
1159 pub const fn wrapping_add(self, rhs: Self) -> Self {
1160 intrinsics::wrapping_add(self, rhs)
1163 /// Wrapping (modular) addition with a signed integer. Computes
1164 /// `self + rhs`, wrapping around at the boundary of the type.
1171 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_add_signed(2), 3);")]
1172 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_add_signed(-2), ", stringify!($SelfT), "::MAX);")]
1173 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).wrapping_add_signed(4), 1);")]
1175 #[stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
1176 #[rustc_const_stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
1177 #[must_use = "this returns the result of the operation, \
1178 without modifying the original"]
1180 pub const fn wrapping_add_signed(self, rhs: $SignedT) -> Self {
1181 self.wrapping_add(rhs as Self)
1184 /// Wrapping (modular) subtraction. Computes `self - rhs`,
1185 /// wrapping around at the boundary of the type.
1192 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);")]
1193 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::MAX), 101);")]
1195 #[stable(feature = "rust1", since = "1.0.0")]
1196 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1197 #[must_use = "this returns the result of the operation, \
1198 without modifying the original"]
1200 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1201 intrinsics::wrapping_sub(self, rhs)
1204 /// Wrapping (modular) multiplication. Computes `self *
1205 /// rhs`, wrapping around at the boundary of the type.
1211 /// Please note that this example is shared between integer types.
1212 /// Which explains why `u8` is used here.
1215 /// assert_eq!(10u8.wrapping_mul(12), 120);
1216 /// assert_eq!(25u8.wrapping_mul(12), 44);
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1220 #[must_use = "this returns the result of the operation, \
1221 without modifying the original"]
1223 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1224 intrinsics::wrapping_mul(self, rhs)
1227 /// Wrapping (modular) division. Computes `self / rhs`.
1228 /// Wrapped division on unsigned types is just normal division.
1229 /// There's no way wrapping could ever happen.
1230 /// This function exists, so that all operations
1231 /// are accounted for in the wrapping operations.
1238 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);")]
1240 #[stable(feature = "num_wrapping", since = "1.2.0")]
1241 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1242 #[must_use = "this returns the result of the operation, \
1243 without modifying the original"]
1245 pub const fn wrapping_div(self, rhs: Self) -> Self {
1249 /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
1250 /// Wrapped division on unsigned types is just normal division.
1251 /// There's no way wrapping could ever happen.
1252 /// This function exists, so that all operations
1253 /// are accounted for in the wrapping operations.
1254 /// Since, for the positive integers, all common
1255 /// definitions of division are equal, this
1256 /// is exactly equal to `self.wrapping_div(rhs)`.
1263 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);")]
1265 #[stable(feature = "euclidean_division", since = "1.38.0")]
1266 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1267 #[must_use = "this returns the result of the operation, \
1268 without modifying the original"]
1270 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
1274 /// Wrapping (modular) remainder. Computes `self % rhs`.
1275 /// Wrapped remainder calculation on unsigned types is
1276 /// just the regular remainder calculation.
1277 /// There's no way wrapping could ever happen.
1278 /// This function exists, so that all operations
1279 /// are accounted for in the wrapping operations.
1286 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);")]
1288 #[stable(feature = "num_wrapping", since = "1.2.0")]
1289 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1290 #[must_use = "this returns the result of the operation, \
1291 without modifying the original"]
1293 pub const fn wrapping_rem(self, rhs: Self) -> Self {
1297 /// Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
1298 /// Wrapped modulo calculation on unsigned types is
1299 /// just the regular remainder calculation.
1300 /// There's no way wrapping could ever happen.
1301 /// This function exists, so that all operations
1302 /// are accounted for in the wrapping operations.
1303 /// Since, for the positive integers, all common
1304 /// definitions of division are equal, this
1305 /// is exactly equal to `self.wrapping_rem(rhs)`.
1312 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);")]
1314 #[stable(feature = "euclidean_division", since = "1.38.0")]
1315 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1316 #[must_use = "this returns the result of the operation, \
1317 without modifying the original"]
1319 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1323 /// Wrapping (modular) negation. Computes `-self`,
1324 /// wrapping around at the boundary of the type.
1326 /// Since unsigned types do not have negative equivalents
1327 /// all applications of this function will wrap (except for `-0`).
1328 /// For values smaller than the corresponding signed type's maximum
1329 /// the result is the same as casting the corresponding signed value.
1330 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
1331 /// `MAX` is the corresponding signed type's maximum.
1337 /// Please note that this example is shared between integer types.
1338 /// Which explains why `i8` is used here.
1341 /// assert_eq!(100i8.wrapping_neg(), -100);
1342 /// assert_eq!((-128i8).wrapping_neg(), -128);
1344 #[stable(feature = "num_wrapping", since = "1.2.0")]
1345 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1346 #[must_use = "this returns the result of the operation, \
1347 without modifying the original"]
1349 pub const fn wrapping_neg(self) -> Self {
1350 (0 as $SelfT).wrapping_sub(self)
1353 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1354 /// where `mask` removes any high-order bits of `rhs` that
1355 /// would cause the shift to exceed the bitwidth of the type.
1357 /// Note that this is *not* the same as a rotate-left; the
1358 /// RHS of a wrapping shift-left is restricted to the range
1359 /// of the type, rather than the bits shifted out of the LHS
1360 /// being returned to the other end. The primitive integer
1361 /// types all implement a [`rotate_left`](Self::rotate_left) function,
1362 /// which may be what you want instead.
1369 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);")]
1370 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);")]
1372 #[stable(feature = "num_wrapping", since = "1.2.0")]
1373 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1374 #[must_use = "this returns the result of the operation, \
1375 without modifying the original"]
1377 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1378 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1381 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1385 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
1386 /// where `mask` removes any high-order bits of `rhs` that
1387 /// would cause the shift to exceed the bitwidth of the type.
1389 /// Note that this is *not* the same as a rotate-right; the
1390 /// RHS of a wrapping shift-right is restricted to the range
1391 /// of the type, rather than the bits shifted out of the LHS
1392 /// being returned to the other end. The primitive integer
1393 /// types all implement a [`rotate_right`](Self::rotate_right) function,
1394 /// which may be what you want instead.
1401 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);")]
1402 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);")]
1404 #[stable(feature = "num_wrapping", since = "1.2.0")]
1405 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1406 #[must_use = "this returns the result of the operation, \
1407 without modifying the original"]
1409 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1410 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1413 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1417 /// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1418 /// wrapping around at the boundary of the type.
1425 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);")]
1426 /// assert_eq!(3u8.wrapping_pow(6), 217);
1428 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1429 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1430 #[must_use = "this returns the result of the operation, \
1431 without modifying the original"]
1433 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
1437 let mut base = self;
1438 let mut acc: Self = 1;
1442 acc = acc.wrapping_mul(base);
1445 base = base.wrapping_mul(base);
1448 // since exp!=0, finally the exp must be 1.
1449 // Deal with the final bit of the exponent separately, since
1450 // squaring the base afterwards is not necessary and may cause a
1451 // needless overflow.
1452 acc.wrapping_mul(base)
1455 /// Calculates `self` + `rhs`
1457 /// Returns a tuple of the addition along with a boolean indicating
1458 /// whether an arithmetic overflow would occur. If an overflow would
1459 /// have occurred then the wrapped value is returned.
1466 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));")]
1467 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));")]
1469 #[stable(feature = "wrapping", since = "1.7.0")]
1470 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1471 #[must_use = "this returns the result of the operation, \
1472 without modifying the original"]
1474 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1475 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1479 /// Calculates `self` + `rhs` + `carry` and returns a tuple containing
1480 /// the sum and the output carry.
1482 /// Performs "ternary addition" of two integer operands and a carry-in
1483 /// bit, and returns an output integer and a carry-out bit. This allows
1484 /// chaining together multiple additions to create a wider addition, and
1485 /// can be useful for bignum addition.
1487 #[doc = concat!("This can be thought of as a ", stringify!($BITS), "-bit \"full adder\", in the electronics sense.")]
1489 /// If the input carry is false, this method is equivalent to
1490 /// [`overflowing_add`](Self::overflowing_add), and the output carry is
1491 /// equal to the overflow flag. Note that although carry and overflow
1492 /// flags are similar for unsigned integers, they are different for
1493 /// signed integers.
1498 /// #![feature(bigint_helper_methods)]
1500 #[doc = concat!("// 3 MAX (a = 3 × 2^", stringify!($BITS), " + 2^", stringify!($BITS), " - 1)")]
1501 #[doc = concat!("// + 5 7 (b = 5 × 2^", stringify!($BITS), " + 7)")]
1503 #[doc = concat!("// 9 6 (sum = 9 × 2^", stringify!($BITS), " + 6)")]
1505 #[doc = concat!("let (a1, a0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (3, ", stringify!($SelfT), "::MAX);")]
1506 #[doc = concat!("let (b1, b0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (5, 7);")]
1507 /// let carry0 = false;
1509 /// let (sum0, carry1) = a0.carrying_add(b0, carry0);
1510 /// assert_eq!(carry1, true);
1511 /// let (sum1, carry2) = a1.carrying_add(b1, carry1);
1512 /// assert_eq!(carry2, false);
1514 /// assert_eq!((sum1, sum0), (9, 6));
1516 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
1517 #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")]
1518 #[must_use = "this returns the result of the operation, \
1519 without modifying the original"]
1521 pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
1522 // note: longer-term this should be done via an intrinsic, but this has been shown
1523 // to generate optimal code for now, and LLVM doesn't have an equivalent intrinsic
1524 let (a, b) = self.overflowing_add(rhs);
1525 let (c, d) = a.overflowing_add(carry as $SelfT);
1529 /// Calculates `self` + `rhs` with a signed `rhs`
1531 /// Returns a tuple of the addition along with a boolean indicating
1532 /// whether an arithmetic overflow would occur. If an overflow would
1533 /// have occurred then the wrapped value is returned.
1540 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_signed(2), (3, false));")]
1541 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_signed(-2), (", stringify!($SelfT), "::MAX, true));")]
1542 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).overflowing_add_signed(4), (1, true));")]
1544 #[stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
1545 #[rustc_const_stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
1546 #[must_use = "this returns the result of the operation, \
1547 without modifying the original"]
1549 pub const fn overflowing_add_signed(self, rhs: $SignedT) -> (Self, bool) {
1550 let (res, overflowed) = self.overflowing_add(rhs as Self);
1551 (res, overflowed ^ (rhs < 0))
1554 /// Calculates `self` - `rhs`
1556 /// Returns a tuple of the subtraction along with a boolean indicating
1557 /// whether an arithmetic overflow would occur. If an overflow would
1558 /// have occurred then the wrapped value is returned.
1565 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));")]
1566 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")]
1568 #[stable(feature = "wrapping", since = "1.7.0")]
1569 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1570 #[must_use = "this returns the result of the operation, \
1571 without modifying the original"]
1573 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1574 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1578 /// Calculates `self` − `rhs` − `borrow` and returns a tuple
1579 /// containing the difference and the output borrow.
1581 /// Performs "ternary subtraction" by subtracting both an integer
1582 /// operand and a borrow-in bit from `self`, and returns an output
1583 /// integer and a borrow-out bit. This allows chaining together multiple
1584 /// subtractions to create a wider subtraction, and can be useful for
1585 /// bignum subtraction.
1590 /// #![feature(bigint_helper_methods)]
1592 #[doc = concat!("// 9 6 (a = 9 × 2^", stringify!($BITS), " + 6)")]
1593 #[doc = concat!("// - 5 7 (b = 5 × 2^", stringify!($BITS), " + 7)")]
1595 #[doc = concat!("// 3 MAX (diff = 3 × 2^", stringify!($BITS), " + 2^", stringify!($BITS), " - 1)")]
1597 #[doc = concat!("let (a1, a0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (9, 6);")]
1598 #[doc = concat!("let (b1, b0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (5, 7);")]
1599 /// let borrow0 = false;
1601 /// let (diff0, borrow1) = a0.borrowing_sub(b0, borrow0);
1602 /// assert_eq!(borrow1, true);
1603 /// let (diff1, borrow2) = a1.borrowing_sub(b1, borrow1);
1604 /// assert_eq!(borrow2, false);
1606 #[doc = concat!("assert_eq!((diff1, diff0), (3, ", stringify!($SelfT), "::MAX));")]
1608 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
1609 #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")]
1610 #[must_use = "this returns the result of the operation, \
1611 without modifying the original"]
1613 pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
1614 // note: longer-term this should be done via an intrinsic, but this has been shown
1615 // to generate optimal code for now, and LLVM doesn't have an equivalent intrinsic
1616 let (a, b) = self.overflowing_sub(rhs);
1617 let (c, d) = a.overflowing_sub(borrow as $SelfT);
1621 /// Computes the absolute difference between `self` and `other`.
1628 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(80), 20", stringify!($SelfT), ");")]
1629 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(110), 10", stringify!($SelfT), ");")]
1631 #[stable(feature = "int_abs_diff", since = "1.60.0")]
1632 #[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
1633 #[must_use = "this returns the result of the operation, \
1634 without modifying the original"]
1636 pub const fn abs_diff(self, other: Self) -> Self {
1637 if mem::size_of::<Self>() == 1 {
1638 // Trick LLVM into generating the psadbw instruction when SSE2
1639 // is available and this function is autovectorized for u8's.
1640 (self as i32).wrapping_sub(other as i32).abs() as Self
1650 /// Calculates the multiplication of `self` and `rhs`.
1652 /// Returns a tuple of the multiplication along with a boolean
1653 /// indicating whether an arithmetic overflow would occur. If an
1654 /// overflow would have occurred then the wrapped value is returned.
1660 /// Please note that this example is shared between integer types.
1661 /// Which explains why `u32` is used here.
1664 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
1665 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
1667 #[stable(feature = "wrapping", since = "1.7.0")]
1668 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1669 #[must_use = "this returns the result of the operation, \
1670 without modifying the original"]
1672 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1673 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1677 /// Calculates the divisor when `self` is divided by `rhs`.
1679 /// Returns a tuple of the divisor along with a boolean indicating
1680 /// whether an arithmetic overflow would occur. Note that for unsigned
1681 /// integers overflow never occurs, so the second value is always
1686 /// This function will panic if `rhs` is 0.
1693 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));")]
1696 #[stable(feature = "wrapping", since = "1.7.0")]
1697 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1698 #[must_use = "this returns the result of the operation, \
1699 without modifying the original"]
1700 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1704 /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1706 /// Returns a tuple of the divisor along with a boolean indicating
1707 /// whether an arithmetic overflow would occur. Note that for unsigned
1708 /// integers overflow never occurs, so the second value is always
1710 /// Since, for the positive integers, all common
1711 /// definitions of division are equal, this
1712 /// is exactly equal to `self.overflowing_div(rhs)`.
1716 /// This function will panic if `rhs` is 0.
1723 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));")]
1726 #[stable(feature = "euclidean_division", since = "1.38.0")]
1727 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1728 #[must_use = "this returns the result of the operation, \
1729 without modifying the original"]
1730 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1734 /// Calculates the remainder when `self` is divided by `rhs`.
1736 /// Returns a tuple of the remainder after dividing along with a boolean
1737 /// indicating whether an arithmetic overflow would occur. Note that for
1738 /// unsigned integers overflow never occurs, so the second value is
1743 /// This function will panic if `rhs` is 0.
1750 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));")]
1753 #[stable(feature = "wrapping", since = "1.7.0")]
1754 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1755 #[must_use = "this returns the result of the operation, \
1756 without modifying the original"]
1757 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1761 /// Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
1763 /// Returns a tuple of the modulo after dividing along with a boolean
1764 /// indicating whether an arithmetic overflow would occur. Note that for
1765 /// unsigned integers overflow never occurs, so the second value is
1767 /// Since, for the positive integers, all common
1768 /// definitions of division are equal, this operation
1769 /// is exactly equal to `self.overflowing_rem(rhs)`.
1773 /// This function will panic if `rhs` is 0.
1780 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));")]
1783 #[stable(feature = "euclidean_division", since = "1.38.0")]
1784 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1785 #[must_use = "this returns the result of the operation, \
1786 without modifying the original"]
1787 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1791 /// Negates self in an overflowing fashion.
1793 /// Returns `!self + 1` using wrapping operations to return the value
1794 /// that represents the negation of this unsigned value. Note that for
1795 /// positive unsigned values overflow always occurs, but negating 0 does
1803 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));")]
1804 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT), ", true));")]
1807 #[stable(feature = "wrapping", since = "1.7.0")]
1808 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1809 #[must_use = "this returns the result of the operation, \
1810 without modifying the original"]
1811 pub const fn overflowing_neg(self) -> (Self, bool) {
1812 ((!self).wrapping_add(1), self != 0)
1815 /// Shifts self left by `rhs` bits.
1817 /// Returns a tuple of the shifted version of self along with a boolean
1818 /// indicating whether the shift value was larger than or equal to the
1819 /// number of bits. If the shift value is too large, then value is
1820 /// masked (N-1) where N is the number of bits, and this value is then
1821 /// used to perform the shift.
1828 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));")]
1829 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));")]
1831 #[stable(feature = "wrapping", since = "1.7.0")]
1832 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1833 #[must_use = "this returns the result of the operation, \
1834 without modifying the original"]
1836 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1837 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1840 /// Shifts self right by `rhs` bits.
1842 /// Returns a tuple of the shifted version of self along with a boolean
1843 /// indicating whether the shift value was larger than or equal to the
1844 /// number of bits. If the shift value is too large, then value is
1845 /// masked (N-1) where N is the number of bits, and this value is then
1846 /// used to perform the shift.
1853 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));")]
1854 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));")]
1856 #[stable(feature = "wrapping", since = "1.7.0")]
1857 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1858 #[must_use = "this returns the result of the operation, \
1859 without modifying the original"]
1861 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1862 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1865 /// Raises self to the power of `exp`, using exponentiation by squaring.
1867 /// Returns a tuple of the exponentiation along with a bool indicating
1868 /// whether an overflow happened.
1875 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));")]
1876 /// assert_eq!(3u8.overflowing_pow(6), (217, true));
1878 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1879 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1880 #[must_use = "this returns the result of the operation, \
1881 without modifying the original"]
1883 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1887 let mut base = self;
1888 let mut acc: Self = 1;
1889 let mut overflown = false;
1890 // Scratch space for storing results of overflowing_mul.
1895 r = acc.overflowing_mul(base);
1900 r = base.overflowing_mul(base);
1905 // since exp!=0, finally the exp must be 1.
1906 // Deal with the final bit of the exponent separately, since
1907 // squaring the base afterwards is not necessary and may cause a
1908 // needless overflow.
1909 r = acc.overflowing_mul(base);
1915 /// Raises self to the power of `exp`, using exponentiation by squaring.
1922 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".pow(5), 32);")]
1924 #[stable(feature = "rust1", since = "1.0.0")]
1925 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1926 #[must_use = "this returns the result of the operation, \
1927 without modifying the original"]
1929 #[rustc_inherit_overflow_checks]
1930 pub const fn pow(self, mut exp: u32) -> Self {
1934 let mut base = self;
1945 // since exp!=0, finally the exp must be 1.
1946 // Deal with the final bit of the exponent separately, since
1947 // squaring the base afterwards is not necessary and may cause a
1948 // needless overflow.
1952 /// Performs Euclidean division.
1954 /// Since, for the positive integers, all common
1955 /// definitions of division are equal, this
1956 /// is exactly equal to `self / rhs`.
1960 /// This function will panic if `rhs` is 0.
1967 #[doc = concat!("assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type")]
1969 #[stable(feature = "euclidean_division", since = "1.38.0")]
1970 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1971 #[must_use = "this returns the result of the operation, \
1972 without modifying the original"]
1974 #[rustc_inherit_overflow_checks]
1975 pub const fn div_euclid(self, rhs: Self) -> Self {
1980 /// Calculates the least remainder of `self (mod rhs)`.
1982 /// Since, for the positive integers, all common
1983 /// definitions of division are equal, this
1984 /// is exactly equal to `self % rhs`.
1988 /// This function will panic if `rhs` is 0.
1995 #[doc = concat!("assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type")]
1997 #[stable(feature = "euclidean_division", since = "1.38.0")]
1998 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1999 #[must_use = "this returns the result of the operation, \
2000 without modifying the original"]
2002 #[rustc_inherit_overflow_checks]
2003 pub const fn rem_euclid(self, rhs: Self) -> Self {
2007 /// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
2009 /// This is the same as performing `self / rhs` for all unsigned integers.
2013 /// This function will panic if `rhs` is zero.
2020 /// #![feature(int_roundings)]
2021 #[doc = concat!("assert_eq!(7_", stringify!($SelfT), ".div_floor(4), 1);")]
2023 #[unstable(feature = "int_roundings", issue = "88581")]
2024 #[must_use = "this returns the result of the operation, \
2025 without modifying the original"]
2027 pub const fn div_floor(self, rhs: Self) -> Self {
2031 /// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
2035 /// This function will panic if `rhs` is zero.
2037 /// ## Overflow behavior
2039 /// On overflow, this function will panic if overflow checks are enabled (default in debug
2040 /// mode) and wrap if overflow checks are disabled (default in release mode).
2047 /// #![feature(int_roundings)]
2048 #[doc = concat!("assert_eq!(7_", stringify!($SelfT), ".div_ceil(4), 2);")]
2050 #[unstable(feature = "int_roundings", issue = "88581")]
2051 #[must_use = "this returns the result of the operation, \
2052 without modifying the original"]
2054 #[rustc_inherit_overflow_checks]
2055 pub const fn div_ceil(self, rhs: Self) -> Self {
2058 if r > 0 && rhs > 0 {
2065 /// Calculates the smallest value greater than or equal to `self` that
2066 /// is a multiple of `rhs`.
2070 /// This function will panic if `rhs` is zero.
2072 /// ## Overflow behavior
2074 /// On overflow, this function will panic if overflow checks are enabled (default in debug
2075 /// mode) and wrap if overflow checks are disabled (default in release mode).
2082 /// #![feature(int_roundings)]
2083 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".next_multiple_of(8), 16);")]
2084 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".next_multiple_of(8), 24);")]
2086 #[unstable(feature = "int_roundings", issue = "88581")]
2087 #[must_use = "this returns the result of the operation, \
2088 without modifying the original"]
2090 #[rustc_inherit_overflow_checks]
2091 pub const fn next_multiple_of(self, rhs: Self) -> Self {
2094 r => self + (rhs - r)
2098 /// Calculates the smallest value greater than or equal to `self` that
2099 /// is a multiple of `rhs`. Returns `None` if `rhs` is zero or the
2100 /// operation would result in overflow.
2107 /// #![feature(int_roundings)]
2108 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(16));")]
2109 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(24));")]
2110 #[doc = concat!("assert_eq!(1_", stringify!($SelfT), ".checked_next_multiple_of(0), None);")]
2111 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_multiple_of(2), None);")]
2113 #[unstable(feature = "int_roundings", issue = "88581")]
2114 #[must_use = "this returns the result of the operation, \
2115 without modifying the original"]
2117 pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
2118 match try_opt!(self.checked_rem(rhs)) {
2120 // rhs - r cannot overflow because r is smaller than rhs
2121 r => self.checked_add(rhs - r)
2125 /// Returns `true` if and only if `self == 2^k` for some `k`.
2132 #[doc = concat!("assert!(16", stringify!($SelfT), ".is_power_of_two());")]
2133 #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_power_of_two());")]
2136 #[stable(feature = "rust1", since = "1.0.0")]
2137 #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
2139 pub const fn is_power_of_two(self) -> bool {
2140 self.count_ones() == 1
2143 // Returns one less than next power of two.
2144 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
2146 // 8u8.one_less_than_next_power_of_two() == 7
2147 // 6u8.one_less_than_next_power_of_two() == 7
2149 // This method cannot overflow, as in the `next_power_of_two`
2150 // overflow cases it instead ends up returning the maximum value
2151 // of the type, and can return 0 for 0.
2153 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2154 const fn one_less_than_next_power_of_two(self) -> Self {
2155 if self <= 1 { return 0; }
2158 // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros.
2159 // That means the shift is always in-bounds, and some processors
2160 // (such as intel pre-haswell) have more efficient ctlz
2161 // intrinsics when the argument is non-zero.
2162 let z = unsafe { intrinsics::ctlz_nonzero(p) };
2166 /// Returns the smallest power of two greater than or equal to `self`.
2168 /// When return value overflows (i.e., `self > (1 << (N-1))` for type
2169 /// `uN`), it panics in debug mode and the return value is wrapped to 0 in
2170 /// release mode (the only situation in which method can return 0).
2177 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);")]
2178 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);")]
2180 #[stable(feature = "rust1", since = "1.0.0")]
2181 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2182 #[must_use = "this returns the result of the operation, \
2183 without modifying the original"]
2185 #[rustc_inherit_overflow_checks]
2186 pub const fn next_power_of_two(self) -> Self {
2187 self.one_less_than_next_power_of_two() + 1
2190 /// Returns the smallest power of two greater than or equal to `n`. If
2191 /// the next power of two is greater than the type's maximum value,
2192 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
2199 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_next_power_of_two(), Some(2));")]
2200 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));")]
2201 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_power_of_two(), None);")]
2204 #[stable(feature = "rust1", since = "1.0.0")]
2205 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2206 #[must_use = "this returns the result of the operation, \
2207 without modifying the original"]
2208 pub const fn checked_next_power_of_two(self) -> Option<Self> {
2209 self.one_less_than_next_power_of_two().checked_add(1)
2212 /// Returns the smallest power of two greater than or equal to `n`. If
2213 /// the next power of two is greater than the type's maximum value,
2214 /// the return value is wrapped to `0`.
2221 /// #![feature(wrapping_next_power_of_two)]
2223 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);")]
2224 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);")]
2225 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_next_power_of_two(), 0);")]
2228 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
2229 reason = "needs decision on wrapping behaviour")]
2230 #[rustc_const_unstable(feature = "wrapping_next_power_of_two", issue = "32463")]
2231 #[must_use = "this returns the result of the operation, \
2232 without modifying the original"]
2233 pub const fn wrapping_next_power_of_two(self) -> Self {
2234 self.one_less_than_next_power_of_two().wrapping_add(1)
2237 /// Return the memory representation of this integer as a byte array in
2238 /// big-endian (network) byte order.
2240 #[doc = $to_xe_bytes_doc]
2245 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();")]
2246 #[doc = concat!("assert_eq!(bytes, ", $be_bytes, ");")]
2248 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2249 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2250 #[must_use = "this returns the result of the operation, \
2251 without modifying the original"]
2253 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2254 self.to_be().to_ne_bytes()
2257 /// Return the memory representation of this integer as a byte array in
2258 /// little-endian byte order.
2260 #[doc = $to_xe_bytes_doc]
2265 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();")]
2266 #[doc = concat!("assert_eq!(bytes, ", $le_bytes, ");")]
2268 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2269 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2270 #[must_use = "this returns the result of the operation, \
2271 without modifying the original"]
2273 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2274 self.to_le().to_ne_bytes()
2277 /// Return the memory representation of this integer as a byte array in
2278 /// native byte order.
2280 /// As the target platform's native endianness is used, portable code
2281 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2284 #[doc = $to_xe_bytes_doc]
2286 /// [`to_be_bytes`]: Self::to_be_bytes
2287 /// [`to_le_bytes`]: Self::to_le_bytes
2292 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();")]
2295 /// if cfg!(target_endian = "big") {
2296 #[doc = concat!(" ", $be_bytes)]
2298 #[doc = concat!(" ", $le_bytes)]
2302 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2303 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2304 #[must_use = "this returns the result of the operation, \
2305 without modifying the original"]
2306 // SAFETY: const sound because integers are plain old datatypes so we can always
2307 // transmute them to arrays of bytes
2309 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2310 // SAFETY: integers are plain old datatypes so we can always transmute them to
2312 unsafe { mem::transmute(self) }
2315 /// Create a native endian integer value from its representation
2316 /// as a byte array in big endian.
2318 #[doc = $from_xe_bytes_doc]
2323 #[doc = concat!("let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");")]
2324 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2327 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2330 #[doc = concat!("fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2331 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2333 #[doc = concat!(" ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())")]
2336 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2337 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2340 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2341 Self::from_be(Self::from_ne_bytes(bytes))
2344 /// Create a native endian integer value from its representation
2345 /// as a byte array in little endian.
2347 #[doc = $from_xe_bytes_doc]
2352 #[doc = concat!("let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");")]
2353 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2356 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2359 #[doc = concat!("fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2360 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2362 #[doc = concat!(" ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())")]
2365 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2366 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2369 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2370 Self::from_le(Self::from_ne_bytes(bytes))
2373 /// Create a native endian integer value from its memory representation
2374 /// as a byte array in native endianness.
2376 /// As the target platform's native endianness is used, portable code
2377 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2378 /// appropriate instead.
2380 /// [`from_be_bytes`]: Self::from_be_bytes
2381 /// [`from_le_bytes`]: Self::from_le_bytes
2383 #[doc = $from_xe_bytes_doc]
2388 #[doc = concat!("let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {")]
2389 #[doc = concat!(" ", $be_bytes, "")]
2391 #[doc = concat!(" ", $le_bytes, "")]
2393 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2396 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2399 #[doc = concat!("fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2400 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2402 #[doc = concat!(" ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())")]
2405 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2406 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2408 // SAFETY: const sound because integers are plain old datatypes so we can always
2409 // transmute to them
2411 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2412 // SAFETY: integers are plain old datatypes so we can always transmute to them
2413 unsafe { mem::transmute(bytes) }
2416 /// New code should prefer to use
2417 #[doc = concat!("[`", stringify!($SelfT), "::MIN", "`] instead.")]
2419 /// Returns the smallest value that can be represented by this integer type.
2420 #[stable(feature = "rust1", since = "1.0.0")]
2423 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2424 #[deprecated(since = "TBD", note = "replaced by the `MIN` associated constant on this type")]
2425 pub const fn min_value() -> Self { Self::MIN }
2427 /// New code should prefer to use
2428 #[doc = concat!("[`", stringify!($SelfT), "::MAX", "`] instead.")]
2430 /// Returns the largest value that can be represented by this integer type.
2431 #[stable(feature = "rust1", since = "1.0.0")]
2434 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2435 #[deprecated(since = "TBD", note = "replaced by the `MAX` associated constant on this type")]
2436 pub const fn max_value() -> Self { Self::MAX }