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 = "1.66.0")]
486 #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
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: u32) -> Self {
912 // SAFETY: the caller must uphold the safety contract for
914 // Any legal shift amount is losslessly representable in the self type.
915 unsafe { intrinsics::unchecked_shl(self, rhs.try_into().ok().unwrap_unchecked()) }
918 /// Checked shift right. Computes `self >> rhs`, returning `None`
919 /// if `rhs` is larger than or equal to the number of bits in `self`.
926 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));")]
927 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);")]
929 #[stable(feature = "wrapping", since = "1.7.0")]
930 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
931 #[must_use = "this returns the result of the operation, \
932 without modifying the original"]
934 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
935 let (a, b) = self.overflowing_shr(rhs);
936 if unlikely!(b) {None} else {Some(a)}
939 /// Unchecked shift right. Computes `self >> rhs`, assuming that
940 /// `rhs` is less than the number of bits in `self`.
944 /// This results in undefined behavior if `rhs` is larger than
945 /// or equal to the number of bits in `self`,
946 /// i.e. when [`checked_shr`] would return `None`.
948 #[doc = concat!("[`checked_shr`]: ", stringify!($SelfT), "::checked_shr")]
950 feature = "unchecked_math",
951 reason = "niche optimization path",
954 #[must_use = "this returns the result of the operation, \
955 without modifying the original"]
956 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
958 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
959 pub const unsafe fn unchecked_shr(self, rhs: u32) -> Self {
960 // SAFETY: the caller must uphold the safety contract for
962 // Any legal shift amount is losslessly representable in the self type.
963 unsafe { intrinsics::unchecked_shr(self, rhs.try_into().ok().unwrap_unchecked()) }
966 /// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
967 /// overflow occurred.
974 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));")]
975 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);")]
977 #[stable(feature = "no_panic_pow", since = "1.34.0")]
978 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
979 #[must_use = "this returns the result of the operation, \
980 without modifying the original"]
982 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
987 let mut acc: Self = 1;
991 acc = try_opt!(acc.checked_mul(base));
994 base = try_opt!(base.checked_mul(base));
997 // since exp!=0, finally the exp must be 1.
998 // Deal with the final bit of the exponent separately, since
999 // squaring the base afterwards is not necessary and may cause a
1000 // needless overflow.
1002 acc.checked_mul(base)
1005 /// Saturating integer addition. Computes `self + rhs`, saturating at
1006 /// the numeric bounds instead of overflowing.
1013 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);")]
1014 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(127), ", stringify!($SelfT), "::MAX);")]
1016 #[stable(feature = "rust1", since = "1.0.0")]
1017 #[must_use = "this returns the result of the operation, \
1018 without modifying the original"]
1019 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1021 pub const fn saturating_add(self, rhs: Self) -> Self {
1022 intrinsics::saturating_add(self, rhs)
1025 /// Saturating addition with a signed integer. Computes `self + rhs`,
1026 /// saturating at the numeric bounds instead of overflowing.
1033 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_signed(2), 3);")]
1034 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_signed(-2), 0);")]
1035 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).saturating_add_signed(4), ", stringify!($SelfT), "::MAX);")]
1037 #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
1038 #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
1039 #[must_use = "this returns the result of the operation, \
1040 without modifying the original"]
1042 pub const fn saturating_add_signed(self, rhs: $SignedT) -> Self {
1043 let (res, overflow) = self.overflowing_add(rhs as Self);
1044 if overflow == (rhs < 0) {
1046 } else if overflow {
1053 /// Saturating integer subtraction. Computes `self - rhs`, saturating
1054 /// at the numeric bounds instead of overflowing.
1061 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);")]
1062 #[doc = concat!("assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);")]
1064 #[stable(feature = "rust1", since = "1.0.0")]
1065 #[must_use = "this returns the result of the operation, \
1066 without modifying the original"]
1067 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1069 pub const fn saturating_sub(self, rhs: Self) -> Self {
1070 intrinsics::saturating_sub(self, rhs)
1073 /// Saturating integer multiplication. Computes `self * rhs`,
1074 /// saturating at the numeric bounds instead of overflowing.
1081 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);")]
1082 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),"::MAX);")]
1084 #[stable(feature = "wrapping", since = "1.7.0")]
1085 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1086 #[must_use = "this returns the result of the operation, \
1087 without modifying the original"]
1089 pub const fn saturating_mul(self, rhs: Self) -> Self {
1090 match self.checked_mul(rhs) {
1096 /// Saturating integer division. Computes `self / rhs`, saturating at the
1097 /// numeric bounds instead of overflowing.
1104 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".saturating_div(2), 2);")]
1109 #[doc = concat!("let _ = 1", stringify!($SelfT), ".saturating_div(0);")]
1112 #[stable(feature = "saturating_div", since = "1.58.0")]
1113 #[rustc_const_stable(feature = "saturating_div", since = "1.58.0")]
1114 #[must_use = "this returns the result of the operation, \
1115 without modifying the original"]
1117 pub const fn saturating_div(self, rhs: Self) -> Self {
1118 // on unsigned types, there is no overflow in integer division
1119 self.wrapping_div(rhs)
1122 /// Saturating integer exponentiation. Computes `self.pow(exp)`,
1123 /// saturating at the numeric bounds instead of overflowing.
1130 #[doc = concat!("assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);")]
1131 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);")]
1133 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1134 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1135 #[must_use = "this returns the result of the operation, \
1136 without modifying the original"]
1138 pub const fn saturating_pow(self, exp: u32) -> Self {
1139 match self.checked_pow(exp) {
1145 /// Wrapping (modular) addition. Computes `self + rhs`,
1146 /// wrapping around at the boundary of the type.
1153 #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);")]
1154 #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);")]
1156 #[stable(feature = "rust1", since = "1.0.0")]
1157 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1158 #[must_use = "this returns the result of the operation, \
1159 without modifying the original"]
1161 pub const fn wrapping_add(self, rhs: Self) -> Self {
1162 intrinsics::wrapping_add(self, rhs)
1165 /// Wrapping (modular) addition with a signed integer. Computes
1166 /// `self + rhs`, wrapping around at the boundary of the type.
1173 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_add_signed(2), 3);")]
1174 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_add_signed(-2), ", stringify!($SelfT), "::MAX);")]
1175 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).wrapping_add_signed(4), 1);")]
1177 #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
1178 #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
1179 #[must_use = "this returns the result of the operation, \
1180 without modifying the original"]
1182 pub const fn wrapping_add_signed(self, rhs: $SignedT) -> Self {
1183 self.wrapping_add(rhs as Self)
1186 /// Wrapping (modular) subtraction. Computes `self - rhs`,
1187 /// wrapping around at the boundary of the type.
1194 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);")]
1195 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::MAX), 101);")]
1197 #[stable(feature = "rust1", since = "1.0.0")]
1198 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1199 #[must_use = "this returns the result of the operation, \
1200 without modifying the original"]
1202 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1203 intrinsics::wrapping_sub(self, rhs)
1206 /// Wrapping (modular) multiplication. Computes `self *
1207 /// rhs`, wrapping around at the boundary of the type.
1213 /// Please note that this example is shared between integer types.
1214 /// Which explains why `u8` is used here.
1217 /// assert_eq!(10u8.wrapping_mul(12), 120);
1218 /// assert_eq!(25u8.wrapping_mul(12), 44);
1220 #[stable(feature = "rust1", since = "1.0.0")]
1221 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1222 #[must_use = "this returns the result of the operation, \
1223 without modifying the original"]
1225 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1226 intrinsics::wrapping_mul(self, rhs)
1229 /// Wrapping (modular) division. Computes `self / rhs`.
1230 /// Wrapped division on unsigned types is just normal division.
1231 /// There's no way wrapping could ever happen.
1232 /// This function exists, so that all operations
1233 /// are accounted for in the wrapping operations.
1240 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);")]
1242 #[stable(feature = "num_wrapping", since = "1.2.0")]
1243 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1244 #[must_use = "this returns the result of the operation, \
1245 without modifying the original"]
1247 pub const fn wrapping_div(self, rhs: Self) -> Self {
1251 /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
1252 /// Wrapped division on unsigned types is just normal division.
1253 /// There's no way wrapping could ever happen.
1254 /// This function exists, so that all operations
1255 /// are accounted for in the wrapping operations.
1256 /// Since, for the positive integers, all common
1257 /// definitions of division are equal, this
1258 /// is exactly equal to `self.wrapping_div(rhs)`.
1265 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);")]
1267 #[stable(feature = "euclidean_division", since = "1.38.0")]
1268 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1269 #[must_use = "this returns the result of the operation, \
1270 without modifying the original"]
1272 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
1276 /// Wrapping (modular) remainder. Computes `self % rhs`.
1277 /// Wrapped remainder calculation on unsigned types is
1278 /// just the regular remainder calculation.
1279 /// There's no way wrapping could ever happen.
1280 /// This function exists, so that all operations
1281 /// are accounted for in the wrapping operations.
1288 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);")]
1290 #[stable(feature = "num_wrapping", since = "1.2.0")]
1291 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1292 #[must_use = "this returns the result of the operation, \
1293 without modifying the original"]
1295 pub const fn wrapping_rem(self, rhs: Self) -> Self {
1299 /// Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
1300 /// Wrapped modulo calculation on unsigned types is
1301 /// just the regular remainder calculation.
1302 /// There's no way wrapping could ever happen.
1303 /// This function exists, so that all operations
1304 /// are accounted for in the wrapping operations.
1305 /// Since, for the positive integers, all common
1306 /// definitions of division are equal, this
1307 /// is exactly equal to `self.wrapping_rem(rhs)`.
1314 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);")]
1316 #[stable(feature = "euclidean_division", since = "1.38.0")]
1317 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1318 #[must_use = "this returns the result of the operation, \
1319 without modifying the original"]
1321 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1325 /// Wrapping (modular) negation. Computes `-self`,
1326 /// wrapping around at the boundary of the type.
1328 /// Since unsigned types do not have negative equivalents
1329 /// all applications of this function will wrap (except for `-0`).
1330 /// For values smaller than the corresponding signed type's maximum
1331 /// the result is the same as casting the corresponding signed value.
1332 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
1333 /// `MAX` is the corresponding signed type's maximum.
1339 /// Please note that this example is shared between integer types.
1340 /// Which explains why `i8` is used here.
1343 /// assert_eq!(100i8.wrapping_neg(), -100);
1344 /// assert_eq!((-128i8).wrapping_neg(), -128);
1346 #[stable(feature = "num_wrapping", since = "1.2.0")]
1347 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1348 #[must_use = "this returns the result of the operation, \
1349 without modifying the original"]
1351 pub const fn wrapping_neg(self) -> Self {
1352 (0 as $SelfT).wrapping_sub(self)
1355 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1356 /// where `mask` removes any high-order bits of `rhs` that
1357 /// would cause the shift to exceed the bitwidth of the type.
1359 /// Note that this is *not* the same as a rotate-left; the
1360 /// RHS of a wrapping shift-left is restricted to the range
1361 /// of the type, rather than the bits shifted out of the LHS
1362 /// being returned to the other end. The primitive integer
1363 /// types all implement a [`rotate_left`](Self::rotate_left) function,
1364 /// which may be what you want instead.
1371 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);")]
1372 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);")]
1374 #[stable(feature = "num_wrapping", since = "1.2.0")]
1375 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1376 #[must_use = "this returns the result of the operation, \
1377 without modifying the original"]
1379 #[rustc_allow_const_fn_unstable(const_inherent_unchecked_arith)]
1380 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1381 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1384 self.unchecked_shl(rhs & ($BITS - 1))
1388 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
1389 /// where `mask` removes any high-order bits of `rhs` that
1390 /// would cause the shift to exceed the bitwidth of the type.
1392 /// Note that this is *not* the same as a rotate-right; the
1393 /// RHS of a wrapping shift-right is restricted to the range
1394 /// of the type, rather than the bits shifted out of the LHS
1395 /// being returned to the other end. The primitive integer
1396 /// types all implement a [`rotate_right`](Self::rotate_right) function,
1397 /// which may be what you want instead.
1404 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);")]
1405 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);")]
1407 #[stable(feature = "num_wrapping", since = "1.2.0")]
1408 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1409 #[must_use = "this returns the result of the operation, \
1410 without modifying the original"]
1412 #[rustc_allow_const_fn_unstable(const_inherent_unchecked_arith)]
1413 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1414 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1417 self.unchecked_shr(rhs & ($BITS - 1))
1421 /// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1422 /// wrapping around at the boundary of the type.
1429 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);")]
1430 /// assert_eq!(3u8.wrapping_pow(6), 217);
1432 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1433 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1434 #[must_use = "this returns the result of the operation, \
1435 without modifying the original"]
1437 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
1441 let mut base = self;
1442 let mut acc: Self = 1;
1446 acc = acc.wrapping_mul(base);
1449 base = base.wrapping_mul(base);
1452 // since exp!=0, finally the exp must be 1.
1453 // Deal with the final bit of the exponent separately, since
1454 // squaring the base afterwards is not necessary and may cause a
1455 // needless overflow.
1456 acc.wrapping_mul(base)
1459 /// Calculates `self` + `rhs`
1461 /// Returns a tuple of the addition along with a boolean indicating
1462 /// whether an arithmetic overflow would occur. If an overflow would
1463 /// have occurred then the wrapped value is returned.
1470 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));")]
1471 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));")]
1473 #[stable(feature = "wrapping", since = "1.7.0")]
1474 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1475 #[must_use = "this returns the result of the operation, \
1476 without modifying the original"]
1478 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1479 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1483 /// Calculates `self` + `rhs` + `carry` and returns a tuple containing
1484 /// the sum and the output carry.
1486 /// Performs "ternary addition" of two integer operands and a carry-in
1487 /// bit, and returns an output integer and a carry-out bit. This allows
1488 /// chaining together multiple additions to create a wider addition, and
1489 /// can be useful for bignum addition.
1491 #[doc = concat!("This can be thought of as a ", stringify!($BITS), "-bit \"full adder\", in the electronics sense.")]
1493 /// If the input carry is false, this method is equivalent to
1494 /// [`overflowing_add`](Self::overflowing_add), and the output carry is
1495 /// equal to the overflow flag. Note that although carry and overflow
1496 /// flags are similar for unsigned integers, they are different for
1497 /// signed integers.
1502 /// #![feature(bigint_helper_methods)]
1504 #[doc = concat!("// 3 MAX (a = 3 × 2^", stringify!($BITS), " + 2^", stringify!($BITS), " - 1)")]
1505 #[doc = concat!("// + 5 7 (b = 5 × 2^", stringify!($BITS), " + 7)")]
1507 #[doc = concat!("// 9 6 (sum = 9 × 2^", stringify!($BITS), " + 6)")]
1509 #[doc = concat!("let (a1, a0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (3, ", stringify!($SelfT), "::MAX);")]
1510 #[doc = concat!("let (b1, b0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (5, 7);")]
1511 /// let carry0 = false;
1513 /// let (sum0, carry1) = a0.carrying_add(b0, carry0);
1514 /// assert_eq!(carry1, true);
1515 /// let (sum1, carry2) = a1.carrying_add(b1, carry1);
1516 /// assert_eq!(carry2, false);
1518 /// assert_eq!((sum1, sum0), (9, 6));
1520 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
1521 #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")]
1522 #[must_use = "this returns the result of the operation, \
1523 without modifying the original"]
1525 pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
1526 // note: longer-term this should be done via an intrinsic, but this has been shown
1527 // to generate optimal code for now, and LLVM doesn't have an equivalent intrinsic
1528 let (a, b) = self.overflowing_add(rhs);
1529 let (c, d) = a.overflowing_add(carry as $SelfT);
1533 /// Calculates `self` + `rhs` with a signed `rhs`
1535 /// Returns a tuple of the addition along with a boolean indicating
1536 /// whether an arithmetic overflow would occur. If an overflow would
1537 /// have occurred then the wrapped value is returned.
1544 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_signed(2), (3, false));")]
1545 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_signed(-2), (", stringify!($SelfT), "::MAX, true));")]
1546 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).overflowing_add_signed(4), (1, true));")]
1548 #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
1549 #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
1550 #[must_use = "this returns the result of the operation, \
1551 without modifying the original"]
1553 pub const fn overflowing_add_signed(self, rhs: $SignedT) -> (Self, bool) {
1554 let (res, overflowed) = self.overflowing_add(rhs as Self);
1555 (res, overflowed ^ (rhs < 0))
1558 /// Calculates `self` - `rhs`
1560 /// Returns a tuple of the subtraction along with a boolean indicating
1561 /// whether an arithmetic overflow would occur. If an overflow would
1562 /// have occurred then the wrapped value is returned.
1569 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));")]
1570 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")]
1572 #[stable(feature = "wrapping", since = "1.7.0")]
1573 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1574 #[must_use = "this returns the result of the operation, \
1575 without modifying the original"]
1577 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1578 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1582 /// Calculates `self` − `rhs` − `borrow` and returns a tuple
1583 /// containing the difference and the output borrow.
1585 /// Performs "ternary subtraction" by subtracting both an integer
1586 /// operand and a borrow-in bit from `self`, and returns an output
1587 /// integer and a borrow-out bit. This allows chaining together multiple
1588 /// subtractions to create a wider subtraction, and can be useful for
1589 /// bignum subtraction.
1594 /// #![feature(bigint_helper_methods)]
1596 #[doc = concat!("// 9 6 (a = 9 × 2^", stringify!($BITS), " + 6)")]
1597 #[doc = concat!("// - 5 7 (b = 5 × 2^", stringify!($BITS), " + 7)")]
1599 #[doc = concat!("// 3 MAX (diff = 3 × 2^", stringify!($BITS), " + 2^", stringify!($BITS), " - 1)")]
1601 #[doc = concat!("let (a1, a0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (9, 6);")]
1602 #[doc = concat!("let (b1, b0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (5, 7);")]
1603 /// let borrow0 = false;
1605 /// let (diff0, borrow1) = a0.borrowing_sub(b0, borrow0);
1606 /// assert_eq!(borrow1, true);
1607 /// let (diff1, borrow2) = a1.borrowing_sub(b1, borrow1);
1608 /// assert_eq!(borrow2, false);
1610 #[doc = concat!("assert_eq!((diff1, diff0), (3, ", stringify!($SelfT), "::MAX));")]
1612 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
1613 #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")]
1614 #[must_use = "this returns the result of the operation, \
1615 without modifying the original"]
1617 pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
1618 // note: longer-term this should be done via an intrinsic, but this has been shown
1619 // to generate optimal code for now, and LLVM doesn't have an equivalent intrinsic
1620 let (a, b) = self.overflowing_sub(rhs);
1621 let (c, d) = a.overflowing_sub(borrow as $SelfT);
1625 /// Computes the absolute difference between `self` and `other`.
1632 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(80), 20", stringify!($SelfT), ");")]
1633 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(110), 10", stringify!($SelfT), ");")]
1635 #[stable(feature = "int_abs_diff", since = "1.60.0")]
1636 #[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
1637 #[must_use = "this returns the result of the operation, \
1638 without modifying the original"]
1640 pub const fn abs_diff(self, other: Self) -> Self {
1641 if mem::size_of::<Self>() == 1 {
1642 // Trick LLVM into generating the psadbw instruction when SSE2
1643 // is available and this function is autovectorized for u8's.
1644 (self as i32).wrapping_sub(other as i32).abs() as Self
1654 /// Calculates the multiplication of `self` and `rhs`.
1656 /// Returns a tuple of the multiplication along with a boolean
1657 /// indicating whether an arithmetic overflow would occur. If an
1658 /// overflow would have occurred then the wrapped value is returned.
1664 /// Please note that this example is shared between integer types.
1665 /// Which explains why `u32` is used here.
1668 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
1669 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
1671 #[stable(feature = "wrapping", since = "1.7.0")]
1672 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1673 #[must_use = "this returns the result of the operation, \
1674 without modifying the original"]
1676 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1677 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1681 /// Calculates the divisor when `self` is divided by `rhs`.
1683 /// Returns a tuple of the divisor along with a boolean indicating
1684 /// whether an arithmetic overflow would occur. Note that for unsigned
1685 /// integers overflow never occurs, so the second value is always
1690 /// This function will panic if `rhs` is 0.
1697 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));")]
1700 #[stable(feature = "wrapping", since = "1.7.0")]
1701 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1702 #[must_use = "this returns the result of the operation, \
1703 without modifying the original"]
1704 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1708 /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1710 /// Returns a tuple of the divisor along with a boolean indicating
1711 /// whether an arithmetic overflow would occur. Note that for unsigned
1712 /// integers overflow never occurs, so the second value is always
1714 /// Since, for the positive integers, all common
1715 /// definitions of division are equal, this
1716 /// is exactly equal to `self.overflowing_div(rhs)`.
1720 /// This function will panic if `rhs` is 0.
1727 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));")]
1730 #[stable(feature = "euclidean_division", since = "1.38.0")]
1731 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1732 #[must_use = "this returns the result of the operation, \
1733 without modifying the original"]
1734 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1738 /// Calculates the remainder when `self` is divided by `rhs`.
1740 /// Returns a tuple of the remainder after dividing along with a boolean
1741 /// indicating whether an arithmetic overflow would occur. Note that for
1742 /// unsigned integers overflow never occurs, so the second value is
1747 /// This function will panic if `rhs` is 0.
1754 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));")]
1757 #[stable(feature = "wrapping", since = "1.7.0")]
1758 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1759 #[must_use = "this returns the result of the operation, \
1760 without modifying the original"]
1761 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1765 /// Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
1767 /// Returns a tuple of the modulo after dividing along with a boolean
1768 /// indicating whether an arithmetic overflow would occur. Note that for
1769 /// unsigned integers overflow never occurs, so the second value is
1771 /// Since, for the positive integers, all common
1772 /// definitions of division are equal, this operation
1773 /// is exactly equal to `self.overflowing_rem(rhs)`.
1777 /// This function will panic if `rhs` is 0.
1784 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));")]
1787 #[stable(feature = "euclidean_division", since = "1.38.0")]
1788 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1789 #[must_use = "this returns the result of the operation, \
1790 without modifying the original"]
1791 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1795 /// Negates self in an overflowing fashion.
1797 /// Returns `!self + 1` using wrapping operations to return the value
1798 /// that represents the negation of this unsigned value. Note that for
1799 /// positive unsigned values overflow always occurs, but negating 0 does
1807 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));")]
1808 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT), ", true));")]
1811 #[stable(feature = "wrapping", since = "1.7.0")]
1812 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1813 #[must_use = "this returns the result of the operation, \
1814 without modifying the original"]
1815 pub const fn overflowing_neg(self) -> (Self, bool) {
1816 ((!self).wrapping_add(1), self != 0)
1819 /// Shifts self left by `rhs` bits.
1821 /// Returns a tuple of the shifted version of self along with a boolean
1822 /// indicating whether the shift value was larger than or equal to the
1823 /// number of bits. If the shift value is too large, then value is
1824 /// masked (N-1) where N is the number of bits, and this value is then
1825 /// used to perform the shift.
1832 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));")]
1833 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));")]
1835 #[stable(feature = "wrapping", since = "1.7.0")]
1836 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1837 #[must_use = "this returns the result of the operation, \
1838 without modifying the original"]
1840 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1841 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1844 /// Shifts self right by `rhs` bits.
1846 /// Returns a tuple of the shifted version of self along with a boolean
1847 /// indicating whether the shift value was larger than or equal to the
1848 /// number of bits. If the shift value is too large, then value is
1849 /// masked (N-1) where N is the number of bits, and this value is then
1850 /// used to perform the shift.
1857 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));")]
1858 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));")]
1860 #[stable(feature = "wrapping", since = "1.7.0")]
1861 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1862 #[must_use = "this returns the result of the operation, \
1863 without modifying the original"]
1865 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1866 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1869 /// Raises self to the power of `exp`, using exponentiation by squaring.
1871 /// Returns a tuple of the exponentiation along with a bool indicating
1872 /// whether an overflow happened.
1879 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));")]
1880 /// assert_eq!(3u8.overflowing_pow(6), (217, true));
1882 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1883 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1884 #[must_use = "this returns the result of the operation, \
1885 without modifying the original"]
1887 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1891 let mut base = self;
1892 let mut acc: Self = 1;
1893 let mut overflown = false;
1894 // Scratch space for storing results of overflowing_mul.
1899 r = acc.overflowing_mul(base);
1904 r = base.overflowing_mul(base);
1909 // since exp!=0, finally the exp must be 1.
1910 // Deal with the final bit of the exponent separately, since
1911 // squaring the base afterwards is not necessary and may cause a
1912 // needless overflow.
1913 r = acc.overflowing_mul(base);
1919 /// Raises self to the power of `exp`, using exponentiation by squaring.
1926 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".pow(5), 32);")]
1928 #[stable(feature = "rust1", since = "1.0.0")]
1929 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1930 #[must_use = "this returns the result of the operation, \
1931 without modifying the original"]
1933 #[rustc_inherit_overflow_checks]
1934 pub const fn pow(self, mut exp: u32) -> Self {
1938 let mut base = self;
1949 // since exp!=0, finally the exp must be 1.
1950 // Deal with the final bit of the exponent separately, since
1951 // squaring the base afterwards is not necessary and may cause a
1952 // needless overflow.
1956 /// Performs Euclidean division.
1958 /// Since, for the positive integers, all common
1959 /// definitions of division are equal, this
1960 /// is exactly equal to `self / rhs`.
1964 /// This function will panic if `rhs` is 0.
1971 #[doc = concat!("assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type")]
1973 #[stable(feature = "euclidean_division", since = "1.38.0")]
1974 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1975 #[must_use = "this returns the result of the operation, \
1976 without modifying the original"]
1978 #[rustc_inherit_overflow_checks]
1979 pub const fn div_euclid(self, rhs: Self) -> Self {
1984 /// Calculates the least remainder of `self (mod rhs)`.
1986 /// Since, for the positive integers, all common
1987 /// definitions of division are equal, this
1988 /// is exactly equal to `self % rhs`.
1992 /// This function will panic if `rhs` is 0.
1999 #[doc = concat!("assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type")]
2001 #[stable(feature = "euclidean_division", since = "1.38.0")]
2002 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
2003 #[must_use = "this returns the result of the operation, \
2004 without modifying the original"]
2006 #[rustc_inherit_overflow_checks]
2007 pub const fn rem_euclid(self, rhs: Self) -> Self {
2011 /// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
2013 /// This is the same as performing `self / rhs` for all unsigned integers.
2017 /// This function will panic if `rhs` is zero.
2024 /// #![feature(int_roundings)]
2025 #[doc = concat!("assert_eq!(7_", stringify!($SelfT), ".div_floor(4), 1);")]
2027 #[unstable(feature = "int_roundings", issue = "88581")]
2028 #[must_use = "this returns the result of the operation, \
2029 without modifying the original"]
2031 pub const fn div_floor(self, rhs: Self) -> Self {
2035 /// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
2039 /// This function will panic if `rhs` is zero.
2041 /// ## Overflow behavior
2043 /// On overflow, this function will panic if overflow checks are enabled (default in debug
2044 /// mode) and wrap if overflow checks are disabled (default in release mode).
2051 /// #![feature(int_roundings)]
2052 #[doc = concat!("assert_eq!(7_", stringify!($SelfT), ".div_ceil(4), 2);")]
2054 #[unstable(feature = "int_roundings", issue = "88581")]
2055 #[must_use = "this returns the result of the operation, \
2056 without modifying the original"]
2058 #[rustc_inherit_overflow_checks]
2059 pub const fn div_ceil(self, rhs: Self) -> Self {
2062 if r > 0 && rhs > 0 {
2069 /// Calculates the smallest value greater than or equal to `self` that
2070 /// is a multiple of `rhs`.
2074 /// This function will panic if `rhs` is zero.
2076 /// ## Overflow behavior
2078 /// On overflow, this function will panic if overflow checks are enabled (default in debug
2079 /// mode) and wrap if overflow checks are disabled (default in release mode).
2086 /// #![feature(int_roundings)]
2087 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".next_multiple_of(8), 16);")]
2088 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".next_multiple_of(8), 24);")]
2090 #[unstable(feature = "int_roundings", issue = "88581")]
2091 #[must_use = "this returns the result of the operation, \
2092 without modifying the original"]
2094 #[rustc_inherit_overflow_checks]
2095 pub const fn next_multiple_of(self, rhs: Self) -> Self {
2098 r => self + (rhs - r)
2102 /// Calculates the smallest value greater than or equal to `self` that
2103 /// is a multiple of `rhs`. Returns `None` if `rhs` is zero or the
2104 /// operation would result in overflow.
2111 /// #![feature(int_roundings)]
2112 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(16));")]
2113 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(24));")]
2114 #[doc = concat!("assert_eq!(1_", stringify!($SelfT), ".checked_next_multiple_of(0), None);")]
2115 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_multiple_of(2), None);")]
2117 #[unstable(feature = "int_roundings", issue = "88581")]
2118 #[must_use = "this returns the result of the operation, \
2119 without modifying the original"]
2121 pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
2122 match try_opt!(self.checked_rem(rhs)) {
2124 // rhs - r cannot overflow because r is smaller than rhs
2125 r => self.checked_add(rhs - r)
2129 /// Returns `true` if and only if `self == 2^k` for some `k`.
2136 #[doc = concat!("assert!(16", stringify!($SelfT), ".is_power_of_two());")]
2137 #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_power_of_two());")]
2140 #[stable(feature = "rust1", since = "1.0.0")]
2141 #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
2143 pub const fn is_power_of_two(self) -> bool {
2144 self.count_ones() == 1
2147 // Returns one less than next power of two.
2148 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
2150 // 8u8.one_less_than_next_power_of_two() == 7
2151 // 6u8.one_less_than_next_power_of_two() == 7
2153 // This method cannot overflow, as in the `next_power_of_two`
2154 // overflow cases it instead ends up returning the maximum value
2155 // of the type, and can return 0 for 0.
2157 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2158 const fn one_less_than_next_power_of_two(self) -> Self {
2159 if self <= 1 { return 0; }
2162 // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros.
2163 // That means the shift is always in-bounds, and some processors
2164 // (such as intel pre-haswell) have more efficient ctlz
2165 // intrinsics when the argument is non-zero.
2166 let z = unsafe { intrinsics::ctlz_nonzero(p) };
2170 /// Returns the smallest power of two greater than or equal to `self`.
2172 /// When return value overflows (i.e., `self > (1 << (N-1))` for type
2173 /// `uN`), it panics in debug mode and the return value is wrapped to 0 in
2174 /// release mode (the only situation in which method can return 0).
2181 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);")]
2182 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);")]
2184 #[stable(feature = "rust1", since = "1.0.0")]
2185 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2186 #[must_use = "this returns the result of the operation, \
2187 without modifying the original"]
2189 #[rustc_inherit_overflow_checks]
2190 pub const fn next_power_of_two(self) -> Self {
2191 self.one_less_than_next_power_of_two() + 1
2194 /// Returns the smallest power of two greater than or equal to `n`. If
2195 /// the next power of two is greater than the type's maximum value,
2196 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
2203 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_next_power_of_two(), Some(2));")]
2204 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));")]
2205 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_power_of_two(), None);")]
2208 #[stable(feature = "rust1", since = "1.0.0")]
2209 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2210 #[must_use = "this returns the result of the operation, \
2211 without modifying the original"]
2212 pub const fn checked_next_power_of_two(self) -> Option<Self> {
2213 self.one_less_than_next_power_of_two().checked_add(1)
2216 /// Returns the smallest power of two greater than or equal to `n`. If
2217 /// the next power of two is greater than the type's maximum value,
2218 /// the return value is wrapped to `0`.
2225 /// #![feature(wrapping_next_power_of_two)]
2227 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);")]
2228 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);")]
2229 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_next_power_of_two(), 0);")]
2232 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
2233 reason = "needs decision on wrapping behaviour")]
2234 #[rustc_const_unstable(feature = "wrapping_next_power_of_two", issue = "32463")]
2235 #[must_use = "this returns the result of the operation, \
2236 without modifying the original"]
2237 pub const fn wrapping_next_power_of_two(self) -> Self {
2238 self.one_less_than_next_power_of_two().wrapping_add(1)
2241 /// Return the memory representation of this integer as a byte array in
2242 /// big-endian (network) byte order.
2244 #[doc = $to_xe_bytes_doc]
2249 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();")]
2250 #[doc = concat!("assert_eq!(bytes, ", $be_bytes, ");")]
2252 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2253 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2254 #[must_use = "this returns the result of the operation, \
2255 without modifying the original"]
2257 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2258 self.to_be().to_ne_bytes()
2261 /// Return the memory representation of this integer as a byte array in
2262 /// little-endian byte order.
2264 #[doc = $to_xe_bytes_doc]
2269 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();")]
2270 #[doc = concat!("assert_eq!(bytes, ", $le_bytes, ");")]
2272 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2273 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2274 #[must_use = "this returns the result of the operation, \
2275 without modifying the original"]
2277 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2278 self.to_le().to_ne_bytes()
2281 /// Return the memory representation of this integer as a byte array in
2282 /// native byte order.
2284 /// As the target platform's native endianness is used, portable code
2285 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2288 #[doc = $to_xe_bytes_doc]
2290 /// [`to_be_bytes`]: Self::to_be_bytes
2291 /// [`to_le_bytes`]: Self::to_le_bytes
2296 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();")]
2299 /// if cfg!(target_endian = "big") {
2300 #[doc = concat!(" ", $be_bytes)]
2302 #[doc = concat!(" ", $le_bytes)]
2306 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2307 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2308 #[must_use = "this returns the result of the operation, \
2309 without modifying the original"]
2310 // SAFETY: const sound because integers are plain old datatypes so we can always
2311 // transmute them to arrays of bytes
2313 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2314 // SAFETY: integers are plain old datatypes so we can always transmute them to
2316 unsafe { mem::transmute(self) }
2319 /// Create a native endian integer value from its representation
2320 /// as a byte array in big endian.
2322 #[doc = $from_xe_bytes_doc]
2327 #[doc = concat!("let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");")]
2328 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2331 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2334 #[doc = concat!("fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2335 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2337 #[doc = concat!(" ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())")]
2340 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2341 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2344 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2345 Self::from_be(Self::from_ne_bytes(bytes))
2348 /// Create a native endian integer value from its representation
2349 /// as a byte array in little endian.
2351 #[doc = $from_xe_bytes_doc]
2356 #[doc = concat!("let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");")]
2357 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2360 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2363 #[doc = concat!("fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2364 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2366 #[doc = concat!(" ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())")]
2369 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2370 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2373 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2374 Self::from_le(Self::from_ne_bytes(bytes))
2377 /// Create a native endian integer value from its memory representation
2378 /// as a byte array in native endianness.
2380 /// As the target platform's native endianness is used, portable code
2381 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2382 /// appropriate instead.
2384 /// [`from_be_bytes`]: Self::from_be_bytes
2385 /// [`from_le_bytes`]: Self::from_le_bytes
2387 #[doc = $from_xe_bytes_doc]
2392 #[doc = concat!("let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {")]
2393 #[doc = concat!(" ", $be_bytes, "")]
2395 #[doc = concat!(" ", $le_bytes, "")]
2397 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2400 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2403 #[doc = concat!("fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2404 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2406 #[doc = concat!(" ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())")]
2409 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2410 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2412 // SAFETY: const sound because integers are plain old datatypes so we can always
2413 // transmute to them
2415 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2416 // SAFETY: integers are plain old datatypes so we can always transmute to them
2417 unsafe { mem::transmute(bytes) }
2420 /// New code should prefer to use
2421 #[doc = concat!("[`", stringify!($SelfT), "::MIN", "`] instead.")]
2423 /// Returns the smallest value that can be represented by this integer type.
2424 #[stable(feature = "rust1", since = "1.0.0")]
2427 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2428 #[deprecated(since = "TBD", note = "replaced by the `MIN` associated constant on this type")]
2429 pub const fn min_value() -> Self { Self::MIN }
2431 /// New code should prefer to use
2432 #[doc = concat!("[`", stringify!($SelfT), "::MAX", "`] instead.")]
2434 /// Returns the largest value that can be represented by this integer type.
2435 #[stable(feature = "rust1", since = "1.0.0")]
2438 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2439 #[deprecated(since = "TBD", note = "replaced by the `MAX` associated constant on this type")]
2440 pub const fn max_value() -> Self { Self::MAX }