1 macro_rules! uint_impl {
2 ($SelfT:ty, $ActualT:ident, $BITS:expr, $MaxV:expr,
3 $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
4 $reversed:expr, $le_bytes:expr, $be_bytes:expr,
5 $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
6 /// The smallest value that can be represented by this integer type.
13 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN, 0);")]
15 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
16 pub const MIN: Self = 0;
18 /// The largest value that can be represented by this integer type,
19 #[doc = concat!("2<sup>", $BITS, "</sup> - 1.")]
26 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($MaxV), ");")]
28 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
29 pub const MAX: Self = !0;
31 /// The size of this integer type in bits.
36 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::BITS, ", stringify!($BITS), ");")]
38 #[stable(feature = "int_bits_const", since = "1.53.0")]
39 pub const BITS: u32 = $BITS;
41 /// Converts a string slice in a given base to an integer.
43 /// The string is expected to be an optional `+` sign
44 /// followed by digits.
45 /// Leading and trailing whitespace represent an error.
46 /// Digits are a subset of these characters, depending on `radix`:
54 /// This function panics if `radix` is not in the range from 2 to 36.
61 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));")]
63 #[stable(feature = "rust1", since = "1.0.0")]
64 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
65 from_str_radix(src, radix)
68 /// Returns the number of ones in the binary representation of `self`.
75 #[doc = concat!("let n = 0b01001100", stringify!($SelfT), ";")]
77 /// assert_eq!(n.count_ones(), 3);
79 #[stable(feature = "rust1", since = "1.0.0")]
80 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
81 #[doc(alias = "popcount")]
82 #[doc(alias = "popcnt")]
84 pub const fn count_ones(self) -> u32 {
85 intrinsics::ctpop(self as $ActualT) as u32
88 /// Returns the number of zeros in the binary representation of `self`.
95 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.count_zeros(), 0);")]
97 #[stable(feature = "rust1", since = "1.0.0")]
98 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
100 pub const fn count_zeros(self) -> u32 {
104 /// Returns the number of leading zeros in the binary representation of `self`.
111 #[doc = concat!("let n = ", stringify!($SelfT), "::MAX >> 2;")]
113 /// assert_eq!(n.leading_zeros(), 2);
115 #[stable(feature = "rust1", since = "1.0.0")]
116 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
118 pub const fn leading_zeros(self) -> u32 {
119 intrinsics::ctlz(self as $ActualT) as u32
122 /// Returns the number of trailing zeros in the binary representation
130 #[doc = concat!("let n = 0b0101000", stringify!($SelfT), ";")]
132 /// assert_eq!(n.trailing_zeros(), 3);
134 #[stable(feature = "rust1", since = "1.0.0")]
135 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
137 pub const fn trailing_zeros(self) -> u32 {
138 intrinsics::cttz(self) as u32
141 /// Returns the number of leading ones in the binary representation of `self`.
148 #[doc = concat!("let n = !(", stringify!($SelfT), "::MAX >> 2);")]
150 /// assert_eq!(n.leading_ones(), 2);
152 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
153 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
155 pub const fn leading_ones(self) -> u32 {
156 (!self).leading_zeros()
159 /// Returns the number of trailing ones in the binary representation
167 #[doc = concat!("let n = 0b1010111", stringify!($SelfT), ";")]
169 /// assert_eq!(n.trailing_ones(), 3);
171 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
172 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
174 pub const fn trailing_ones(self) -> u32 {
175 (!self).trailing_zeros()
178 /// Shifts the bits to the left by a specified amount, `n`,
179 /// wrapping the truncated bits to the end of the resulting integer.
181 /// Please note this isn't the same operation as the `<<` shifting operator!
188 #[doc = concat!("let n = ", $rot_op, stringify!($SelfT), ";")]
189 #[doc = concat!("let m = ", $rot_result, ";")]
191 #[doc = concat!("assert_eq!(n.rotate_left(", $rot, "), m);")]
193 #[stable(feature = "rust1", since = "1.0.0")]
194 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
195 #[must_use = "this returns the result of the operation, \
196 without modifying the original"]
198 pub const fn rotate_left(self, n: u32) -> Self {
199 intrinsics::rotate_left(self, n as $SelfT)
202 /// Shifts the bits to the right by a specified amount, `n`,
203 /// wrapping the truncated bits to the beginning of the resulting
206 /// Please note this isn't the same operation as the `>>` shifting operator!
213 #[doc = concat!("let n = ", $rot_result, stringify!($SelfT), ";")]
214 #[doc = concat!("let m = ", $rot_op, ";")]
216 #[doc = concat!("assert_eq!(n.rotate_right(", $rot, "), m);")]
218 #[stable(feature = "rust1", since = "1.0.0")]
219 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
220 #[must_use = "this returns the result of the operation, \
221 without modifying the original"]
223 pub const fn rotate_right(self, n: u32) -> Self {
224 intrinsics::rotate_right(self, n as $SelfT)
227 /// Reverses the byte order of the integer.
234 #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
235 /// let m = n.swap_bytes();
237 #[doc = concat!("assert_eq!(m, ", $swapped, ");")]
239 #[stable(feature = "rust1", since = "1.0.0")]
240 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
242 pub const fn swap_bytes(self) -> Self {
243 intrinsics::bswap(self as $ActualT) as Self
246 /// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
247 /// second least-significant bit becomes second most-significant bit, etc.
254 #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
255 /// let m = n.reverse_bits();
257 #[doc = concat!("assert_eq!(m, ", $reversed, ");")]
258 #[doc = concat!("assert_eq!(0, 0", stringify!($SelfT), ".reverse_bits());")]
260 #[stable(feature = "reverse_bits", since = "1.37.0")]
261 #[rustc_const_stable(feature = "const_math", since = "1.37.0")]
264 pub const fn reverse_bits(self) -> Self {
265 intrinsics::bitreverse(self as $ActualT) as Self
268 /// Converts an integer from big endian to the target's endianness.
270 /// On big endian this is a no-op. On little endian the bytes are
278 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
280 /// if cfg!(target_endian = "big") {
281 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_be(n), n)")]
283 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())")]
286 #[stable(feature = "rust1", since = "1.0.0")]
287 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
289 pub const fn from_be(x: Self) -> Self {
290 #[cfg(target_endian = "big")]
294 #[cfg(not(target_endian = "big"))]
300 /// Converts an integer from little endian to the target's endianness.
302 /// On little endian this is a no-op. On big endian the bytes are
310 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
312 /// if cfg!(target_endian = "little") {
313 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_le(n), n)")]
315 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())")]
318 #[stable(feature = "rust1", since = "1.0.0")]
319 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
321 pub const fn from_le(x: Self) -> Self {
322 #[cfg(target_endian = "little")]
326 #[cfg(not(target_endian = "little"))]
332 /// Converts `self` to big endian from the target's endianness.
334 /// On big endian this is a no-op. On little endian the bytes are
342 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
344 /// if cfg!(target_endian = "big") {
345 /// assert_eq!(n.to_be(), n)
347 /// assert_eq!(n.to_be(), n.swap_bytes())
350 #[stable(feature = "rust1", since = "1.0.0")]
351 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
353 pub const fn to_be(self) -> Self { // or not to be?
354 #[cfg(target_endian = "big")]
358 #[cfg(not(target_endian = "big"))]
364 /// Converts `self` to little endian from the target's endianness.
366 /// On little endian this is a no-op. On big endian the bytes are
374 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
376 /// if cfg!(target_endian = "little") {
377 /// assert_eq!(n.to_le(), n)
379 /// assert_eq!(n.to_le(), n.swap_bytes())
382 #[stable(feature = "rust1", since = "1.0.0")]
383 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
385 pub const fn to_le(self) -> Self {
386 #[cfg(target_endian = "little")]
390 #[cfg(not(target_endian = "little"))]
396 /// Checked integer addition. Computes `self + rhs`, returning `None`
397 /// if overflow occurred.
405 "assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(1), ",
406 "Some(", stringify!($SelfT), "::MAX - 1));"
408 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);")]
410 #[stable(feature = "rust1", since = "1.0.0")]
411 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
412 #[must_use = "this returns the result of the operation, \
413 without modifying the original"]
415 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
416 let (a, b) = self.overflowing_add(rhs);
417 if unlikely!(b) {None} else {Some(a)}
420 /// Unchecked integer addition. Computes `self + rhs`, assuming overflow
425 /// This results in undefined behavior when
426 #[doc = concat!("`self + rhs > ", stringify!($SelfT), "::MAX` or `self + rhs < ", stringify!($SelfT), "::MIN`,")]
427 /// i.e. when [`checked_add`] would return `None`.
429 #[doc = concat!("[`checked_add`]: ", stringify!($SelfT), "::checked_add")]
431 feature = "unchecked_math",
432 reason = "niche optimization path",
435 #[must_use = "this returns the result of the operation, \
436 without modifying the original"]
437 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
439 pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
440 // SAFETY: the caller must uphold the safety contract for
442 unsafe { intrinsics::unchecked_add(self, rhs) }
445 /// Checked integer subtraction. Computes `self - rhs`, returning
446 /// `None` if overflow occurred.
453 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));")]
454 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);")]
456 #[stable(feature = "rust1", since = "1.0.0")]
457 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
458 #[must_use = "this returns the result of the operation, \
459 without modifying the original"]
461 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
462 let (a, b) = self.overflowing_sub(rhs);
463 if unlikely!(b) {None} else {Some(a)}
466 /// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
471 /// This results in undefined behavior when
472 #[doc = concat!("`self - rhs > ", stringify!($SelfT), "::MAX` or `self - rhs < ", stringify!($SelfT), "::MIN`,")]
473 /// i.e. when [`checked_sub`] would return `None`.
475 #[doc = concat!("[`checked_sub`]: ", stringify!($SelfT), "::checked_sub")]
477 feature = "unchecked_math",
478 reason = "niche optimization path",
481 #[must_use = "this returns the result of the operation, \
482 without modifying the original"]
483 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
485 pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
486 // SAFETY: the caller must uphold the safety contract for
488 unsafe { intrinsics::unchecked_sub(self, rhs) }
491 /// Checked integer multiplication. Computes `self * rhs`, returning
492 /// `None` if overflow occurred.
499 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));")]
500 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);")]
502 #[stable(feature = "rust1", since = "1.0.0")]
503 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
504 #[must_use = "this returns the result of the operation, \
505 without modifying the original"]
507 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
508 let (a, b) = self.overflowing_mul(rhs);
509 if unlikely!(b) {None} else {Some(a)}
512 /// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
517 /// This results in undefined behavior when
518 #[doc = concat!("`self * rhs > ", stringify!($SelfT), "::MAX` or `self * rhs < ", stringify!($SelfT), "::MIN`,")]
519 /// i.e. when [`checked_mul`] would return `None`.
521 #[doc = concat!("[`checked_mul`]: ", stringify!($SelfT), "::checked_mul")]
523 feature = "unchecked_math",
524 reason = "niche optimization path",
527 #[must_use = "this returns the result of the operation, \
528 without modifying the original"]
529 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
531 pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
532 // SAFETY: the caller must uphold the safety contract for
534 unsafe { intrinsics::unchecked_mul(self, rhs) }
537 /// Checked integer division. Computes `self / rhs`, returning `None`
545 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));")]
546 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);")]
548 #[stable(feature = "rust1", since = "1.0.0")]
549 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.52.0")]
550 #[must_use = "this returns the result of the operation, \
551 without modifying the original"]
553 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
554 if unlikely!(rhs == 0) {
557 // SAFETY: div by zero has been checked above and unsigned types have no other
558 // failure modes for division
559 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
563 /// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
571 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));")]
572 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);")]
574 #[stable(feature = "euclidean_division", since = "1.38.0")]
575 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
576 #[must_use = "this returns the result of the operation, \
577 without modifying the original"]
579 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
580 if unlikely!(rhs == 0) {
583 Some(self.div_euclid(rhs))
588 /// Checked integer remainder. Computes `self % rhs`, returning `None`
596 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));")]
597 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);")]
599 #[stable(feature = "wrapping", since = "1.7.0")]
600 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.52.0")]
601 #[must_use = "this returns the result of the operation, \
602 without modifying the original"]
604 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
605 if unlikely!(rhs == 0) {
608 // SAFETY: div by zero has been checked above and unsigned types have no other
609 // failure modes for division
610 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
614 /// Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
622 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));")]
623 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);")]
625 #[stable(feature = "euclidean_division", since = "1.38.0")]
626 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
627 #[must_use = "this returns the result of the operation, \
628 without modifying the original"]
630 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
631 if unlikely!(rhs == 0) {
634 Some(self.rem_euclid(rhs))
638 /// Returns the logarithm of the number with respect to an arbitrary base,
641 /// This method might not be optimized owing to implementation details;
642 /// `log2` can produce results more efficiently for base 2, and `log10`
643 /// can produce results more efficiently for base 10.
647 /// When the number is negative, zero, or if the base is not at least 2;
648 /// it panics in debug mode and the return value is 0 in release mode.
653 /// #![feature(int_log)]
654 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".log(5), 1);")]
656 #[unstable(feature = "int_log", issue = "70887")]
657 #[must_use = "this returns the result of the operation, \
658 without modifying the original"]
661 #[rustc_inherit_overflow_checks]
662 #[allow(arithmetic_overflow)]
663 pub const fn log(self, base: Self) -> u32 {
664 match self.checked_log(base) {
667 // In debug builds, trigger a panic on None.
668 // This should optimize completely out in release builds.
669 let _ = Self::MAX + 1;
676 /// Returns the base 2 logarithm of the number, rounded down.
680 /// When the number is negative or zero it panics in debug mode and
681 /// the return value is 0 in release mode.
686 /// #![feature(int_log)]
687 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".log2(), 1);")]
689 #[unstable(feature = "int_log", issue = "70887")]
690 #[must_use = "this returns the result of the operation, \
691 without modifying the original"]
694 #[rustc_inherit_overflow_checks]
695 #[allow(arithmetic_overflow)]
696 pub const fn log2(self) -> u32 {
697 match self.checked_log2() {
700 // In debug builds, trigger a panic on None.
701 // This should optimize completely out in release builds.
702 let _ = Self::MAX + 1;
709 /// Returns the base 10 logarithm of the number, rounded down.
713 /// When the number is negative or zero it panics in debug mode and the
714 /// return value is 0 in release mode.
719 /// #![feature(int_log)]
720 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".log10(), 1);")]
722 #[unstable(feature = "int_log", issue = "70887")]
723 #[must_use = "this returns the result of the operation, \
724 without modifying the original"]
727 #[rustc_inherit_overflow_checks]
728 #[allow(arithmetic_overflow)]
729 pub const fn log10(self) -> u32 {
730 match self.checked_log10() {
733 // In debug builds, trigger a panic on None.
734 // This should optimize completely out in release builds.
735 let _ = Self::MAX + 1;
742 /// Returns the logarithm of the number with respect to an arbitrary base,
745 /// Returns `None` if the number is zero, or if the base is not at least 2.
747 /// This method might not be optimized owing to implementation details;
748 /// `checked_log2` can produce results more efficiently for base 2, and
749 /// `checked_log10` can produce results more efficiently for base 10.
754 /// #![feature(int_log)]
755 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_log(5), Some(1));")]
757 #[unstable(feature = "int_log", issue = "70887")]
758 #[must_use = "this returns the result of the operation, \
759 without modifying the original"]
761 pub const fn checked_log(self, base: Self) -> Option<u32> {
762 if self <= 0 || base <= 1 {
768 // Optimization for 128 bit wide integers.
769 if Self::BITS == 128 {
770 let b = Self::log2(self) / (Self::log2(base) + 1);
772 r /= base.pow(b as u32);
783 /// Returns the base 2 logarithm of the number, rounded down.
785 /// Returns `None` if the number is zero.
790 /// #![feature(int_log)]
791 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_log2(), Some(1));")]
793 #[unstable(feature = "int_log", issue = "70887")]
794 #[must_use = "this returns the result of the operation, \
795 without modifying the original"]
797 pub const fn checked_log2(self) -> Option<u32> {
801 // SAFETY: We just checked that this number is positive
802 let log = (Self::BITS - 1) - unsafe { intrinsics::ctlz_nonzero(self) as u32 };
807 /// Returns the base 10 logarithm of the number, rounded down.
809 /// Returns `None` if the number is zero.
814 /// #![feature(int_log)]
815 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_log10(), Some(1));")]
817 #[unstable(feature = "int_log", issue = "70887")]
818 #[must_use = "this returns the result of the operation, \
819 without modifying the original"]
821 pub const fn checked_log10(self) -> Option<u32> {
822 int_log10::$ActualT(self as $ActualT)
825 /// Checked negation. Computes `-self`, returning `None` unless `self ==
828 /// Note that negating any positive integer will overflow.
835 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));")]
836 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);")]
838 #[stable(feature = "wrapping", since = "1.7.0")]
839 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
841 pub const fn checked_neg(self) -> Option<Self> {
842 let (a, b) = self.overflowing_neg();
843 if unlikely!(b) {None} else {Some(a)}
846 /// Checked shift left. Computes `self << rhs`, returning `None`
847 /// if `rhs` is larger than or equal to the number of bits in `self`.
854 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));")]
855 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);")]
857 #[stable(feature = "wrapping", since = "1.7.0")]
858 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
859 #[must_use = "this returns the result of the operation, \
860 without modifying the original"]
862 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
863 let (a, b) = self.overflowing_shl(rhs);
864 if unlikely!(b) {None} else {Some(a)}
867 /// Unchecked shift left. Computes `self << rhs`, assuming that
868 /// `rhs` is less than the number of bits in `self`.
872 /// This results in undefined behavior if `rhs` is larger than
873 /// or equal to the number of bits in `self`,
874 /// i.e. when [`checked_shl`] would return `None`.
876 #[doc = concat!("[`checked_shl`]: ", stringify!($SelfT), "::checked_shl")]
878 feature = "unchecked_math",
879 reason = "niche optimization path",
882 #[must_use = "this returns the result of the operation, \
883 without modifying the original"]
884 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
886 pub const unsafe fn unchecked_shl(self, rhs: Self) -> Self {
887 // SAFETY: the caller must uphold the safety contract for
889 unsafe { intrinsics::unchecked_shl(self, rhs) }
892 /// Checked shift right. Computes `self >> rhs`, returning `None`
893 /// if `rhs` is larger than or equal to the number of bits in `self`.
900 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));")]
901 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);")]
903 #[stable(feature = "wrapping", since = "1.7.0")]
904 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
905 #[must_use = "this returns the result of the operation, \
906 without modifying the original"]
908 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
909 let (a, b) = self.overflowing_shr(rhs);
910 if unlikely!(b) {None} else {Some(a)}
913 /// Unchecked shift right. Computes `self >> rhs`, assuming that
914 /// `rhs` is less than the number of bits in `self`.
918 /// This results in undefined behavior if `rhs` is larger than
919 /// or equal to the number of bits in `self`,
920 /// i.e. when [`checked_shr`] would return `None`.
922 #[doc = concat!("[`checked_shr`]: ", stringify!($SelfT), "::checked_shr")]
924 feature = "unchecked_math",
925 reason = "niche optimization path",
928 #[must_use = "this returns the result of the operation, \
929 without modifying the original"]
930 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
932 pub const unsafe fn unchecked_shr(self, rhs: Self) -> Self {
933 // SAFETY: the caller must uphold the safety contract for
935 unsafe { intrinsics::unchecked_shr(self, rhs) }
938 /// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
939 /// overflow occurred.
946 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));")]
947 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);")]
949 #[stable(feature = "no_panic_pow", since = "1.34.0")]
950 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
951 #[must_use = "this returns the result of the operation, \
952 without modifying the original"]
954 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
959 let mut acc: Self = 1;
963 acc = try_opt!(acc.checked_mul(base));
966 base = try_opt!(base.checked_mul(base));
969 // since exp!=0, finally the exp must be 1.
970 // Deal with the final bit of the exponent separately, since
971 // squaring the base afterwards is not necessary and may cause a
972 // needless overflow.
974 Some(try_opt!(acc.checked_mul(base)))
977 /// Saturating integer addition. Computes `self + rhs`, saturating at
978 /// the numeric bounds instead of overflowing.
985 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);")]
986 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(127), ", stringify!($SelfT), "::MAX);")]
988 #[stable(feature = "rust1", since = "1.0.0")]
989 #[must_use = "this returns the result of the operation, \
990 without modifying the original"]
991 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
993 pub const fn saturating_add(self, rhs: Self) -> Self {
994 intrinsics::saturating_add(self, rhs)
997 /// Saturating integer subtraction. Computes `self - rhs`, saturating
998 /// at the numeric bounds instead of overflowing.
1005 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);")]
1006 #[doc = concat!("assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);")]
1008 #[stable(feature = "rust1", since = "1.0.0")]
1009 #[must_use = "this returns the result of the operation, \
1010 without modifying the original"]
1011 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1013 pub const fn saturating_sub(self, rhs: Self) -> Self {
1014 intrinsics::saturating_sub(self, rhs)
1017 /// Saturating integer multiplication. Computes `self * rhs`,
1018 /// saturating at the numeric bounds instead of overflowing.
1025 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);")]
1026 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),"::MAX);")]
1028 #[stable(feature = "wrapping", since = "1.7.0")]
1029 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1030 #[must_use = "this returns the result of the operation, \
1031 without modifying the original"]
1033 pub const fn saturating_mul(self, rhs: Self) -> Self {
1034 match self.checked_mul(rhs) {
1040 /// Saturating integer division. Computes `self / rhs`, saturating at the
1041 /// numeric bounds instead of overflowing.
1048 /// #![feature(saturating_div)]
1050 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".saturating_div(2), 2);")]
1055 /// #![feature(saturating_div)]
1057 #[doc = concat!("let _ = 1", stringify!($SelfT), ".saturating_div(0);")]
1060 #[unstable(feature = "saturating_div", issue = "87920")]
1061 #[rustc_const_unstable(feature = "saturating_div", issue = "87920")]
1062 #[must_use = "this returns the result of the operation, \
1063 without modifying the original"]
1065 pub const fn saturating_div(self, rhs: Self) -> Self {
1066 // on unsigned types, there is no overflow in integer division
1067 self.wrapping_div(rhs)
1070 /// Saturating integer exponentiation. Computes `self.pow(exp)`,
1071 /// saturating at the numeric bounds instead of overflowing.
1078 #[doc = concat!("assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);")]
1079 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);")]
1081 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1082 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1083 #[must_use = "this returns the result of the operation, \
1084 without modifying the original"]
1086 pub const fn saturating_pow(self, exp: u32) -> Self {
1087 match self.checked_pow(exp) {
1093 /// Wrapping (modular) addition. Computes `self + rhs`,
1094 /// wrapping around at the boundary of the type.
1101 #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);")]
1102 #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);")]
1104 #[stable(feature = "rust1", since = "1.0.0")]
1105 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1106 #[must_use = "this returns the result of the operation, \
1107 without modifying the original"]
1109 pub const fn wrapping_add(self, rhs: Self) -> Self {
1110 intrinsics::wrapping_add(self, rhs)
1113 /// Wrapping (modular) subtraction. Computes `self - rhs`,
1114 /// wrapping around at the boundary of the type.
1121 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);")]
1122 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::MAX), 101);")]
1124 #[stable(feature = "rust1", since = "1.0.0")]
1125 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1126 #[must_use = "this returns the result of the operation, \
1127 without modifying the original"]
1129 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1130 intrinsics::wrapping_sub(self, rhs)
1133 /// Wrapping (modular) multiplication. Computes `self *
1134 /// rhs`, wrapping around at the boundary of the type.
1140 /// Please note that this example is shared between integer types.
1141 /// Which explains why `u8` is used here.
1144 /// assert_eq!(10u8.wrapping_mul(12), 120);
1145 /// assert_eq!(25u8.wrapping_mul(12), 44);
1147 #[stable(feature = "rust1", since = "1.0.0")]
1148 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1149 #[must_use = "this returns the result of the operation, \
1150 without modifying the original"]
1152 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1153 intrinsics::wrapping_mul(self, rhs)
1156 /// Wrapping (modular) division. Computes `self / rhs`.
1157 /// Wrapped division on unsigned types is just normal division.
1158 /// There's no way wrapping could ever happen.
1159 /// This function exists, so that all operations
1160 /// are accounted for in the wrapping operations.
1167 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);")]
1169 #[stable(feature = "num_wrapping", since = "1.2.0")]
1170 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1171 #[must_use = "this returns the result of the operation, \
1172 without modifying the original"]
1174 pub const fn wrapping_div(self, rhs: Self) -> Self {
1178 /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
1179 /// Wrapped division on unsigned types is just normal division.
1180 /// There's no way wrapping could ever happen.
1181 /// This function exists, so that all operations
1182 /// are accounted for in the wrapping operations.
1183 /// Since, for the positive integers, all common
1184 /// definitions of division are equal, this
1185 /// is exactly equal to `self.wrapping_div(rhs)`.
1192 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);")]
1194 #[stable(feature = "euclidean_division", since = "1.38.0")]
1195 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1196 #[must_use = "this returns the result of the operation, \
1197 without modifying the original"]
1199 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
1203 /// Wrapping (modular) remainder. Computes `self % rhs`.
1204 /// Wrapped remainder calculation on unsigned types is
1205 /// just the regular remainder calculation.
1206 /// There's no way wrapping could ever happen.
1207 /// This function exists, so that all operations
1208 /// are accounted for in the wrapping operations.
1215 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);")]
1217 #[stable(feature = "num_wrapping", since = "1.2.0")]
1218 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1219 #[must_use = "this returns the result of the operation, \
1220 without modifying the original"]
1222 pub const fn wrapping_rem(self, rhs: Self) -> Self {
1226 /// Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
1227 /// Wrapped modulo calculation on unsigned types is
1228 /// just the regular remainder calculation.
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.
1232 /// Since, for the positive integers, all common
1233 /// definitions of division are equal, this
1234 /// is exactly equal to `self.wrapping_rem(rhs)`.
1241 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);")]
1243 #[stable(feature = "euclidean_division", since = "1.38.0")]
1244 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1245 #[must_use = "this returns the result of the operation, \
1246 without modifying the original"]
1248 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1252 /// Wrapping (modular) negation. Computes `-self`,
1253 /// wrapping around at the boundary of the type.
1255 /// Since unsigned types do not have negative equivalents
1256 /// all applications of this function will wrap (except for `-0`).
1257 /// For values smaller than the corresponding signed type's maximum
1258 /// the result is the same as casting the corresponding signed value.
1259 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
1260 /// `MAX` is the corresponding signed type's maximum.
1266 /// Please note that this example is shared between integer types.
1267 /// Which explains why `i8` is used here.
1270 /// assert_eq!(100i8.wrapping_neg(), -100);
1271 /// assert_eq!((-128i8).wrapping_neg(), -128);
1273 #[stable(feature = "num_wrapping", since = "1.2.0")]
1274 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1276 pub const fn wrapping_neg(self) -> Self {
1277 (0 as $SelfT).wrapping_sub(self)
1280 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1281 /// where `mask` removes any high-order bits of `rhs` that
1282 /// would cause the shift to exceed the bitwidth of the type.
1284 /// Note that this is *not* the same as a rotate-left; the
1285 /// RHS of a wrapping shift-left is restricted to the range
1286 /// of the type, rather than the bits shifted out of the LHS
1287 /// being returned to the other end. The primitive integer
1288 /// types all implement a [`rotate_left`](Self::rotate_left) function,
1289 /// which may be what you want instead.
1296 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);")]
1297 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);")]
1299 #[stable(feature = "num_wrapping", since = "1.2.0")]
1300 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1301 #[must_use = "this returns the result of the operation, \
1302 without modifying the original"]
1304 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1305 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1308 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1312 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
1313 /// where `mask` removes any high-order bits of `rhs` that
1314 /// would cause the shift to exceed the bitwidth of the type.
1316 /// Note that this is *not* the same as a rotate-right; the
1317 /// RHS of a wrapping shift-right is restricted to the range
1318 /// of the type, rather than the bits shifted out of the LHS
1319 /// being returned to the other end. The primitive integer
1320 /// types all implement a [`rotate_right`](Self::rotate_right) function,
1321 /// which may be what you want instead.
1328 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);")]
1329 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);")]
1331 #[stable(feature = "num_wrapping", since = "1.2.0")]
1332 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1333 #[must_use = "this returns the result of the operation, \
1334 without modifying the original"]
1336 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1337 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1340 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1344 /// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1345 /// wrapping around at the boundary of the type.
1352 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);")]
1353 /// assert_eq!(3u8.wrapping_pow(6), 217);
1355 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1356 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1357 #[must_use = "this returns the result of the operation, \
1358 without modifying the original"]
1360 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
1364 let mut base = self;
1365 let mut acc: Self = 1;
1369 acc = acc.wrapping_mul(base);
1372 base = base.wrapping_mul(base);
1375 // since exp!=0, finally the exp must be 1.
1376 // Deal with the final bit of the exponent separately, since
1377 // squaring the base afterwards is not necessary and may cause a
1378 // needless overflow.
1379 acc.wrapping_mul(base)
1382 /// Calculates `self` + `rhs`
1384 /// Returns a tuple of the addition along with a boolean indicating
1385 /// whether an arithmetic overflow would occur. If an overflow would
1386 /// have occurred then the wrapped value is returned.
1394 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));")]
1395 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));")]
1397 #[stable(feature = "wrapping", since = "1.7.0")]
1398 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1399 #[must_use = "this returns the result of the operation, \
1400 without modifying the original"]
1402 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1403 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1407 /// Calculates `self + rhs + carry` without the ability to overflow.
1409 /// Performs "ternary addition" which takes in an extra bit to add, and may return an
1410 /// additional bit of overflow. This allows for chaining together multiple additions
1411 /// to create "big integers" which represent larger values.
1418 /// #![feature(bigint_helper_methods)]
1419 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".carrying_add(2, false), (7, false));")]
1420 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".carrying_add(2, true), (8, false));")]
1421 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.carrying_add(1, false), (0, true));")]
1422 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.carrying_add(1, true), (1, true));")]
1424 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
1425 #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")]
1426 #[must_use = "this returns the result of the operation, \
1427 without modifying the original"]
1429 pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
1430 // note: longer-term this should be done via an intrinsic, but this has been shown
1431 // to generate optimal code for now, and LLVM doesn't have an equivalent intrinsic
1432 let (a, b) = self.overflowing_add(rhs);
1433 let (c, d) = a.overflowing_add(carry as $SelfT);
1437 /// Calculates `self` - `rhs`
1439 /// Returns a tuple of the subtraction along with a boolean indicating
1440 /// whether an arithmetic overflow would occur. If an overflow would
1441 /// have occurred then the wrapped value is returned.
1449 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));")]
1450 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")]
1452 #[stable(feature = "wrapping", since = "1.7.0")]
1453 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1454 #[must_use = "this returns the result of the operation, \
1455 without modifying the original"]
1457 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1458 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1462 /// Calculates `self - rhs - borrow` without the ability to overflow.
1464 /// Performs "ternary subtraction" which takes in an extra bit to subtract, and may return
1465 /// an additional bit of overflow. This allows for chaining together multiple subtractions
1466 /// to create "big integers" which represent larger values.
1473 /// #![feature(bigint_helper_methods)]
1474 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".borrowing_sub(2, false), (3, false));")]
1475 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".borrowing_sub(2, true), (2, false));")]
1476 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".borrowing_sub(1, false), (", stringify!($SelfT), "::MAX, true));")]
1477 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".borrowing_sub(1, true), (", stringify!($SelfT), "::MAX - 1, true));")]
1479 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
1480 #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")]
1481 #[must_use = "this returns the result of the operation, \
1482 without modifying the original"]
1484 pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
1485 // note: longer-term this should be done via an intrinsic, but this has been shown
1486 // to generate optimal code for now, and LLVM doesn't have an equivalent intrinsic
1487 let (a, b) = self.overflowing_sub(rhs);
1488 let (c, d) = a.overflowing_sub(borrow as $SelfT);
1492 /// Calculates the multiplication of `self` and `rhs`.
1494 /// Returns a tuple of the multiplication along with a boolean
1495 /// indicating whether an arithmetic overflow would occur. If an
1496 /// overflow would have occurred then the wrapped value is returned.
1502 /// Please note that this example is shared between integer types.
1503 /// Which explains why `u32` is used here.
1506 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
1507 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
1509 #[stable(feature = "wrapping", since = "1.7.0")]
1510 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1511 #[must_use = "this returns the result of the operation, \
1512 without modifying the original"]
1514 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1515 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1519 /// Calculates the divisor when `self` is divided by `rhs`.
1521 /// Returns a tuple of the divisor along with a boolean indicating
1522 /// whether an arithmetic overflow would occur. Note that for unsigned
1523 /// integers overflow never occurs, so the second value is always
1528 /// This function will panic if `rhs` is 0.
1535 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));")]
1538 #[stable(feature = "wrapping", since = "1.7.0")]
1539 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1540 #[must_use = "this returns the result of the operation, \
1541 without modifying the original"]
1542 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1546 /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1548 /// Returns a tuple of the divisor along with a boolean indicating
1549 /// whether an arithmetic overflow would occur. Note that for unsigned
1550 /// integers overflow never occurs, so the second value is always
1552 /// Since, for the positive integers, all common
1553 /// definitions of division are equal, this
1554 /// is exactly equal to `self.overflowing_div(rhs)`.
1558 /// This function will panic if `rhs` is 0.
1565 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));")]
1568 #[stable(feature = "euclidean_division", since = "1.38.0")]
1569 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1570 #[must_use = "this returns the result of the operation, \
1571 without modifying the original"]
1572 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1576 /// Calculates the remainder when `self` is divided by `rhs`.
1578 /// Returns a tuple of the remainder after dividing along with a boolean
1579 /// indicating whether an arithmetic overflow would occur. Note that for
1580 /// unsigned integers overflow never occurs, so the second value is
1585 /// This function will panic if `rhs` is 0.
1592 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));")]
1595 #[stable(feature = "wrapping", since = "1.7.0")]
1596 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1597 #[must_use = "this returns the result of the operation, \
1598 without modifying the original"]
1599 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1603 /// Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
1605 /// Returns a tuple of the modulo after dividing along with a boolean
1606 /// indicating whether an arithmetic overflow would occur. Note that for
1607 /// unsigned integers overflow never occurs, so the second value is
1609 /// Since, for the positive integers, all common
1610 /// definitions of division are equal, this operation
1611 /// is exactly equal to `self.overflowing_rem(rhs)`.
1615 /// This function will panic if `rhs` is 0.
1622 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));")]
1625 #[stable(feature = "euclidean_division", since = "1.38.0")]
1626 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1627 #[must_use = "this returns the result of the operation, \
1628 without modifying the original"]
1629 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1633 /// Negates self in an overflowing fashion.
1635 /// Returns `!self + 1` using wrapping operations to return the value
1636 /// that represents the negation of this unsigned value. Note that for
1637 /// positive unsigned values overflow always occurs, but negating 0 does
1645 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));")]
1646 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT), ", true));")]
1649 #[stable(feature = "wrapping", since = "1.7.0")]
1650 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1651 pub const fn overflowing_neg(self) -> (Self, bool) {
1652 ((!self).wrapping_add(1), self != 0)
1655 /// Shifts self left by `rhs` bits.
1657 /// Returns a tuple of the shifted version of self along with a boolean
1658 /// indicating whether the shift value was larger than or equal to the
1659 /// number of bits. If the shift value is too large, then value is
1660 /// masked (N-1) where N is the number of bits, and this value is then
1661 /// used to perform the shift.
1668 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));")]
1669 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, 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_shl(self, rhs: u32) -> (Self, bool) {
1677 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1680 /// Shifts self right by `rhs` bits.
1682 /// Returns a tuple of the shifted version of self along with a boolean
1683 /// indicating whether the shift value was larger than or equal to the
1684 /// number of bits. If the shift value is too large, then value is
1685 /// masked (N-1) where N is the number of bits, and this value is then
1686 /// used to perform the shift.
1693 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));")]
1694 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));")]
1696 #[stable(feature = "wrapping", since = "1.7.0")]
1697 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1698 #[must_use = "this returns the result of the operation, \
1699 without modifying the original"]
1701 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1702 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1705 /// Raises self to the power of `exp`, using exponentiation by squaring.
1707 /// Returns a tuple of the exponentiation along with a bool indicating
1708 /// whether an overflow happened.
1715 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));")]
1716 /// assert_eq!(3u8.overflowing_pow(6), (217, true));
1718 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1719 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1720 #[must_use = "this returns the result of the operation, \
1721 without modifying the original"]
1723 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1727 let mut base = self;
1728 let mut acc: Self = 1;
1729 let mut overflown = false;
1730 // Scratch space for storing results of overflowing_mul.
1735 r = acc.overflowing_mul(base);
1740 r = base.overflowing_mul(base);
1745 // since exp!=0, finally the exp must be 1.
1746 // Deal with the final bit of the exponent separately, since
1747 // squaring the base afterwards is not necessary and may cause a
1748 // needless overflow.
1749 r = acc.overflowing_mul(base);
1755 /// Raises self to the power of `exp`, using exponentiation by squaring.
1762 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".pow(5), 32);")]
1764 #[stable(feature = "rust1", since = "1.0.0")]
1765 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1766 #[must_use = "this returns the result of the operation, \
1767 without modifying the original"]
1769 #[rustc_inherit_overflow_checks]
1770 pub const fn pow(self, mut exp: u32) -> Self {
1774 let mut base = self;
1785 // since exp!=0, finally the exp must be 1.
1786 // Deal with the final bit of the exponent separately, since
1787 // squaring the base afterwards is not necessary and may cause a
1788 // needless overflow.
1792 /// Performs Euclidean division.
1794 /// Since, for the positive integers, all common
1795 /// definitions of division are equal, this
1796 /// is exactly equal to `self / rhs`.
1800 /// This function will panic if `rhs` is 0.
1807 #[doc = concat!("assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type")]
1809 #[stable(feature = "euclidean_division", since = "1.38.0")]
1810 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1811 #[must_use = "this returns the result of the operation, \
1812 without modifying the original"]
1814 #[rustc_inherit_overflow_checks]
1815 pub const fn div_euclid(self, rhs: Self) -> Self {
1820 /// Calculates the least remainder of `self (mod rhs)`.
1822 /// Since, for the positive integers, all common
1823 /// definitions of division are equal, this
1824 /// is exactly equal to `self % rhs`.
1828 /// This function will panic if `rhs` is 0.
1835 #[doc = concat!("assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type")]
1837 #[stable(feature = "euclidean_division", since = "1.38.0")]
1838 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1839 #[must_use = "this returns the result of the operation, \
1840 without modifying the original"]
1842 #[rustc_inherit_overflow_checks]
1843 pub const fn rem_euclid(self, rhs: Self) -> Self {
1847 /// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
1849 /// This is the same as performing `self / rhs` for all unsigned integers.
1853 /// This function will panic if `rhs` is 0.
1860 /// #![feature(int_roundings)]
1861 #[doc = concat!("assert_eq!(7_", stringify!($SelfT), ".div_floor(4), 1);")]
1863 #[unstable(feature = "int_roundings", issue = "88581")]
1865 #[rustc_inherit_overflow_checks]
1866 pub const fn div_floor(self, rhs: Self) -> Self {
1870 /// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
1874 /// This function will panic if `rhs` is 0.
1881 /// #![feature(int_roundings)]
1882 #[doc = concat!("assert_eq!(7_", stringify!($SelfT), ".div_ceil(4), 2);")]
1884 #[unstable(feature = "int_roundings", issue = "88581")]
1886 #[rustc_inherit_overflow_checks]
1887 pub const fn div_ceil(self, rhs: Self) -> Self {
1890 if r > 0 && rhs > 0 {
1897 /// Calculates the smallest value greater than or equal to `self` that
1898 /// is a multiple of `rhs`.
1902 /// This function will panic if `rhs` is 0 or the operation results in overflow.
1909 /// #![feature(int_roundings)]
1910 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".next_multiple_of(8), 16);")]
1911 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".next_multiple_of(8), 24);")]
1913 #[unstable(feature = "int_roundings", issue = "88581")]
1914 #[must_use = "this returns the result of the operation, \
1915 without modifying the original"]
1917 #[rustc_inherit_overflow_checks]
1918 pub const fn next_multiple_of(self, rhs: Self) -> Self {
1921 r => self + (rhs - r)
1925 /// Calculates the smallest value greater than or equal to `self` that
1926 /// is a multiple of `rhs`. If `rhs` is negative,
1933 /// #![feature(int_roundings)]
1934 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(16));")]
1935 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(24));")]
1936 #[doc = concat!("assert_eq!(1_", stringify!($SelfT), ".checked_next_multiple_of(0), None);")]
1937 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_multiple_of(2), None);")]
1939 #[unstable(feature = "int_roundings", issue = "88581")]
1940 #[must_use = "this returns the result of the operation, \
1941 without modifying the original"]
1943 #[rustc_inherit_overflow_checks]
1944 pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
1945 match try_opt!(self.checked_rem(rhs)) {
1947 r => self.checked_add(try_opt!(rhs.checked_sub(r)))
1951 /// Returns `true` if and only if `self == 2^k` for some `k`.
1958 #[doc = concat!("assert!(16", stringify!($SelfT), ".is_power_of_two());")]
1959 #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_power_of_two());")]
1961 #[stable(feature = "rust1", since = "1.0.0")]
1962 #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
1964 pub const fn is_power_of_two(self) -> bool {
1965 self.count_ones() == 1
1968 // Returns one less than next power of two.
1969 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
1971 // 8u8.one_less_than_next_power_of_two() == 7
1972 // 6u8.one_less_than_next_power_of_two() == 7
1974 // This method cannot overflow, as in the `next_power_of_two`
1975 // overflow cases it instead ends up returning the maximum value
1976 // of the type, and can return 0 for 0.
1978 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1979 const fn one_less_than_next_power_of_two(self) -> Self {
1980 if self <= 1 { return 0; }
1983 // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros.
1984 // That means the shift is always in-bounds, and some processors
1985 // (such as intel pre-haswell) have more efficient ctlz
1986 // intrinsics when the argument is non-zero.
1987 let z = unsafe { intrinsics::ctlz_nonzero(p) };
1991 /// Returns the smallest power of two greater than or equal to `self`.
1993 /// When return value overflows (i.e., `self > (1 << (N-1))` for type
1994 /// `uN`), it panics in debug mode and the return value is wrapped to 0 in
1995 /// release mode (the only situation in which method can return 0).
2002 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);")]
2003 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);")]
2005 #[stable(feature = "rust1", since = "1.0.0")]
2006 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2008 #[rustc_inherit_overflow_checks]
2009 pub const fn next_power_of_two(self) -> Self {
2010 self.one_less_than_next_power_of_two() + 1
2013 /// Returns the smallest power of two greater than or equal to `n`. If
2014 /// the next power of two is greater than the type's maximum value,
2015 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
2022 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_next_power_of_two(), Some(2));")]
2023 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));")]
2024 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_power_of_two(), None);")]
2027 #[stable(feature = "rust1", since = "1.0.0")]
2028 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2029 pub const fn checked_next_power_of_two(self) -> Option<Self> {
2030 self.one_less_than_next_power_of_two().checked_add(1)
2033 /// Returns the smallest power of two greater than or equal to `n`. If
2034 /// the next power of two is greater than the type's maximum value,
2035 /// the return value is wrapped to `0`.
2042 /// #![feature(wrapping_next_power_of_two)]
2044 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);")]
2045 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);")]
2046 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_next_power_of_two(), 0);")]
2048 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
2049 reason = "needs decision on wrapping behaviour")]
2050 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2051 pub const fn wrapping_next_power_of_two(self) -> Self {
2052 self.one_less_than_next_power_of_two().wrapping_add(1)
2055 /// Return the memory representation of this integer as a byte array in
2056 /// big-endian (network) byte order.
2058 #[doc = $to_xe_bytes_doc]
2063 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();")]
2064 #[doc = concat!("assert_eq!(bytes, ", $be_bytes, ");")]
2066 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2067 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2069 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2070 self.to_be().to_ne_bytes()
2073 /// Return the memory representation of this integer as a byte array in
2074 /// little-endian byte order.
2076 #[doc = $to_xe_bytes_doc]
2081 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();")]
2082 #[doc = concat!("assert_eq!(bytes, ", $le_bytes, ");")]
2084 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2085 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2087 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2088 self.to_le().to_ne_bytes()
2091 /// Return the memory representation of this integer as a byte array in
2092 /// native byte order.
2094 /// As the target platform's native endianness is used, portable code
2095 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2098 #[doc = $to_xe_bytes_doc]
2100 /// [`to_be_bytes`]: Self::to_be_bytes
2101 /// [`to_le_bytes`]: Self::to_le_bytes
2106 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();")]
2109 /// if cfg!(target_endian = "big") {
2110 #[doc = concat!(" ", $be_bytes)]
2112 #[doc = concat!(" ", $le_bytes)]
2116 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2117 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2118 // SAFETY: const sound because integers are plain old datatypes so we can always
2119 // transmute them to arrays of bytes
2120 #[cfg_attr(bootstrap, rustc_allow_const_fn_unstable(const_fn_transmute))]
2122 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2123 // SAFETY: integers are plain old datatypes so we can always transmute them to
2125 unsafe { mem::transmute(self) }
2128 /// Create a native endian integer value from its representation
2129 /// as a byte array in big endian.
2131 #[doc = $from_xe_bytes_doc]
2136 #[doc = concat!("let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");")]
2137 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2140 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2143 /// use std::convert::TryInto;
2145 #[doc = concat!("fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2146 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2148 #[doc = concat!(" ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())")]
2151 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2152 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2154 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2155 Self::from_be(Self::from_ne_bytes(bytes))
2158 /// Create a native endian integer value from its representation
2159 /// as a byte array in little endian.
2161 #[doc = $from_xe_bytes_doc]
2166 #[doc = concat!("let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");")]
2167 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2170 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2173 /// use std::convert::TryInto;
2175 #[doc = concat!("fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2176 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2178 #[doc = concat!(" ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())")]
2181 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2182 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2184 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2185 Self::from_le(Self::from_ne_bytes(bytes))
2188 /// Create a native endian integer value from its memory representation
2189 /// as a byte array in native endianness.
2191 /// As the target platform's native endianness is used, portable code
2192 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2193 /// appropriate instead.
2195 /// [`from_be_bytes`]: Self::from_be_bytes
2196 /// [`from_le_bytes`]: Self::from_le_bytes
2198 #[doc = $from_xe_bytes_doc]
2203 #[doc = concat!("let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {")]
2204 #[doc = concat!(" ", $be_bytes, "")]
2206 #[doc = concat!(" ", $le_bytes, "")]
2208 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2211 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2214 /// use std::convert::TryInto;
2216 #[doc = concat!("fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2217 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2219 #[doc = concat!(" ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())")]
2222 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2223 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2224 // SAFETY: const sound because integers are plain old datatypes so we can always
2225 // transmute to them
2226 #[cfg_attr(bootstrap, rustc_allow_const_fn_unstable(const_fn_transmute))]
2228 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2229 // SAFETY: integers are plain old datatypes so we can always transmute to them
2230 unsafe { mem::transmute(bytes) }
2233 /// New code should prefer to use
2234 #[doc = concat!("[`", stringify!($SelfT), "::MIN", "`] instead.")]
2236 /// Returns the smallest value that can be represented by this integer type.
2237 #[stable(feature = "rust1", since = "1.0.0")]
2240 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2241 #[rustc_deprecated(since = "TBD", reason = "replaced by the `MIN` associated constant on this type")]
2242 pub const fn min_value() -> Self { Self::MIN }
2244 /// New code should prefer to use
2245 #[doc = concat!("[`", stringify!($SelfT), "::MAX", "`] instead.")]
2247 /// Returns the largest value that can be represented by this integer type.
2248 #[stable(feature = "rust1", since = "1.0.0")]
2251 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2252 #[rustc_deprecated(since = "TBD", reason = "replaced by the `MAX` associated constant on this type")]
2253 pub const fn max_value() -> Self { Self::MAX }