1 macro_rules! int_impl {
2 ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $BITS_MINUS_ONE:expr, $Min:expr, $Max: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,
7 #[doc = concat!("-2<sup>", $BITS_MINUS_ONE, "</sup>.")]
14 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN, ", stringify!($Min), ");")]
16 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
17 pub const MIN: Self = !0 ^ ((!0 as $UnsignedT) >> 1) as Self;
19 /// The largest value that can be represented by this integer type,
20 #[doc = concat!("2<sup>", $BITS_MINUS_ONE, "</sup> - 1.")]
27 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($Max), ");")]
29 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
30 pub const MAX: Self = !Self::MIN;
32 /// The size of this integer type in bits.
37 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::BITS, ", stringify!($BITS), ");")]
39 #[stable(feature = "int_bits_const", since = "1.53.0")]
40 pub const BITS: u32 = $BITS;
42 /// Converts a string slice in a given base to an integer.
44 /// The string is expected to be an optional `+` or `-` sign followed by digits.
45 /// Leading and trailing whitespace represent an error. Digits are a subset of these characters,
46 /// 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 = 0b100_0000", stringify!($SelfT), ";")]
77 /// assert_eq!(n.count_ones(), 1);
80 #[stable(feature = "rust1", since = "1.0.0")]
81 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
82 #[doc(alias = "popcount")]
83 #[doc(alias = "popcnt")]
85 pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
87 /// Returns the number of zeros in the binary representation of `self`.
94 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.count_zeros(), 1);")]
96 #[stable(feature = "rust1", since = "1.0.0")]
97 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
99 pub const fn count_zeros(self) -> u32 {
103 /// Returns the number of leading zeros in the binary representation of `self`.
110 #[doc = concat!("let n = -1", stringify!($SelfT), ";")]
112 /// assert_eq!(n.leading_zeros(), 0);
114 #[stable(feature = "rust1", since = "1.0.0")]
115 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
117 pub const fn leading_zeros(self) -> u32 {
118 (self as $UnsignedT).leading_zeros()
121 /// Returns the number of trailing zeros in the binary representation of `self`.
128 #[doc = concat!("let n = -4", stringify!($SelfT), ";")]
130 /// assert_eq!(n.trailing_zeros(), 2);
132 #[stable(feature = "rust1", since = "1.0.0")]
133 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
135 pub const fn trailing_zeros(self) -> u32 {
136 (self as $UnsignedT).trailing_zeros()
139 /// Returns the number of leading ones in the binary representation of `self`.
146 #[doc = concat!("let n = -1", stringify!($SelfT), ";")]
148 #[doc = concat!("assert_eq!(n.leading_ones(), ", stringify!($BITS), ");")]
150 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
151 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
153 pub const fn leading_ones(self) -> u32 {
154 (self as $UnsignedT).leading_ones()
157 /// Returns the number of trailing ones in the binary representation of `self`.
164 #[doc = concat!("let n = 3", stringify!($SelfT), ";")]
166 /// assert_eq!(n.trailing_ones(), 2);
168 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
169 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
171 pub const fn trailing_ones(self) -> u32 {
172 (self as $UnsignedT).trailing_ones()
175 /// Shifts the bits to the left by a specified amount, `n`,
176 /// wrapping the truncated bits to the end of the resulting integer.
178 /// Please note this isn't the same operation as the `<<` shifting operator!
185 #[doc = concat!("let n = ", $rot_op, stringify!($SelfT), ";")]
186 #[doc = concat!("let m = ", $rot_result, ";")]
188 #[doc = concat!("assert_eq!(n.rotate_left(", $rot, "), m);")]
190 #[stable(feature = "rust1", since = "1.0.0")]
191 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
192 #[must_use = "this returns the result of the operation, \
193 without modifying the original"]
195 pub const fn rotate_left(self, n: u32) -> Self {
196 (self as $UnsignedT).rotate_left(n) as Self
199 /// Shifts the bits to the right by a specified amount, `n`,
200 /// wrapping the truncated bits to the beginning of the resulting
203 /// Please note this isn't the same operation as the `>>` shifting operator!
210 #[doc = concat!("let n = ", $rot_result, stringify!($SelfT), ";")]
211 #[doc = concat!("let m = ", $rot_op, ";")]
213 #[doc = concat!("assert_eq!(n.rotate_right(", $rot, "), m);")]
215 #[stable(feature = "rust1", since = "1.0.0")]
216 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
217 #[must_use = "this returns the result of the operation, \
218 without modifying the original"]
220 pub const fn rotate_right(self, n: u32) -> Self {
221 (self as $UnsignedT).rotate_right(n) as Self
224 /// Reverses the byte order of the integer.
231 #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
233 /// let m = n.swap_bytes();
235 #[doc = concat!("assert_eq!(m, ", $swapped, ");")]
237 #[stable(feature = "rust1", since = "1.0.0")]
238 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
240 pub const fn swap_bytes(self) -> Self {
241 (self as $UnsignedT).swap_bytes() as Self
244 /// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
245 /// second least-significant bit becomes second most-significant bit, etc.
252 #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
253 /// let m = n.reverse_bits();
255 #[doc = concat!("assert_eq!(m, ", $reversed, ");")]
256 #[doc = concat!("assert_eq!(0, 0", stringify!($SelfT), ".reverse_bits());")]
258 #[stable(feature = "reverse_bits", since = "1.37.0")]
259 #[rustc_const_stable(feature = "const_int_methods", since = "1.37.0")]
262 pub const fn reverse_bits(self) -> Self {
263 (self as $UnsignedT).reverse_bits() as Self
266 /// Converts an integer from big endian to the target's endianness.
268 /// On big endian this is a no-op. On little endian the bytes are swapped.
275 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
277 /// if cfg!(target_endian = "big") {
278 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_be(n), n)")]
280 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())")]
283 #[stable(feature = "rust1", since = "1.0.0")]
284 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
286 pub const fn from_be(x: Self) -> Self {
287 #[cfg(target_endian = "big")]
291 #[cfg(not(target_endian = "big"))]
297 /// Converts an integer from little endian to the target's endianness.
299 /// On little endian this is a no-op. On big endian the bytes are swapped.
306 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
308 /// if cfg!(target_endian = "little") {
309 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_le(n), n)")]
311 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())")]
314 #[stable(feature = "rust1", since = "1.0.0")]
315 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
317 pub const fn from_le(x: Self) -> Self {
318 #[cfg(target_endian = "little")]
322 #[cfg(not(target_endian = "little"))]
328 /// Converts `self` to big endian from the target's endianness.
330 /// On big endian this is a no-op. On little endian the bytes are swapped.
337 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
339 /// if cfg!(target_endian = "big") {
340 /// assert_eq!(n.to_be(), n)
342 /// assert_eq!(n.to_be(), n.swap_bytes())
345 #[stable(feature = "rust1", since = "1.0.0")]
346 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
348 pub const fn to_be(self) -> Self { // or not to be?
349 #[cfg(target_endian = "big")]
353 #[cfg(not(target_endian = "big"))]
359 /// Converts `self` to little endian from the target's endianness.
361 /// On little endian this is a no-op. On big endian the bytes are swapped.
368 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
370 /// if cfg!(target_endian = "little") {
371 /// assert_eq!(n.to_le(), n)
373 /// assert_eq!(n.to_le(), n.swap_bytes())
376 #[stable(feature = "rust1", since = "1.0.0")]
377 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
379 pub const fn to_le(self) -> Self {
380 #[cfg(target_endian = "little")]
384 #[cfg(not(target_endian = "little"))]
390 /// Checked integer addition. Computes `self + rhs`, returning `None`
391 /// if overflow occurred.
398 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(1), Some(", stringify!($SelfT), "::MAX - 1));")]
399 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);")]
401 #[stable(feature = "rust1", since = "1.0.0")]
402 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
403 #[must_use = "this returns the result of the operation, \
404 without modifying the original"]
406 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
407 let (a, b) = self.overflowing_add(rhs);
408 if unlikely!(b) {None} else {Some(a)}
411 /// Unchecked integer addition. Computes `self + rhs`, assuming overflow
416 /// This results in undefined behavior when
417 #[doc = concat!("`self + rhs > ", stringify!($SelfT), "::MAX` or `self + rhs < ", stringify!($SelfT), "::MIN`,")]
418 /// i.e. when [`checked_add`] would return `None`.
420 #[doc = concat!("[`checked_add`]: ", stringify!($SelfT), "::checked_add")]
422 feature = "unchecked_math",
423 reason = "niche optimization path",
426 #[must_use = "this returns the result of the operation, \
427 without modifying the original"]
428 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
430 pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
431 // SAFETY: the caller must uphold the safety contract for
433 unsafe { intrinsics::unchecked_add(self, rhs) }
436 /// Checked addition with an unsigned integer. Computes `self + rhs`,
437 /// returning `None` if overflow occurred.
444 /// # #![feature(mixed_integer_ops)]
445 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_add_unsigned(2), Some(3));")]
446 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add_unsigned(3), None);")]
448 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
449 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
450 #[must_use = "this returns the result of the operation, \
451 without modifying the original"]
453 pub const fn checked_add_unsigned(self, rhs: $UnsignedT) -> Option<Self> {
454 let (a, b) = self.overflowing_add_unsigned(rhs);
455 if unlikely!(b) {None} else {Some(a)}
458 /// Checked integer subtraction. Computes `self - rhs`, returning `None` if
459 /// overflow occurred.
466 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 2).checked_sub(1), Some(", stringify!($SelfT), "::MIN + 1));")]
467 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 2).checked_sub(3), None);")]
469 #[stable(feature = "rust1", since = "1.0.0")]
470 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
471 #[must_use = "this returns the result of the operation, \
472 without modifying the original"]
474 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
475 let (a, b) = self.overflowing_sub(rhs);
476 if unlikely!(b) {None} else {Some(a)}
479 /// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
484 /// This results in undefined behavior when
485 #[doc = concat!("`self - rhs > ", stringify!($SelfT), "::MAX` or `self - rhs < ", stringify!($SelfT), "::MIN`,")]
486 /// i.e. when [`checked_sub`] would return `None`.
488 #[doc = concat!("[`checked_sub`]: ", stringify!($SelfT), "::checked_sub")]
490 feature = "unchecked_math",
491 reason = "niche optimization path",
494 #[must_use = "this returns the result of the operation, \
495 without modifying the original"]
496 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
498 pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
499 // SAFETY: the caller must uphold the safety contract for
501 unsafe { intrinsics::unchecked_sub(self, rhs) }
504 /// Checked subtraction with an unsigned integer. Computes `self - rhs`,
505 /// returning `None` if overflow occurred.
512 /// # #![feature(mixed_integer_ops)]
513 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_sub_unsigned(2), Some(-1));")]
514 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 2).checked_sub_unsigned(3), None);")]
516 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
517 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
518 #[must_use = "this returns the result of the operation, \
519 without modifying the original"]
521 pub const fn checked_sub_unsigned(self, rhs: $UnsignedT) -> Option<Self> {
522 let (a, b) = self.overflowing_sub_unsigned(rhs);
523 if unlikely!(b) {None} else {Some(a)}
526 /// Checked integer multiplication. Computes `self * rhs`, returning `None` if
527 /// overflow occurred.
534 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(1), Some(", stringify!($SelfT), "::MAX));")]
535 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);")]
537 #[stable(feature = "rust1", since = "1.0.0")]
538 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
539 #[must_use = "this returns the result of the operation, \
540 without modifying the original"]
542 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
543 let (a, b) = self.overflowing_mul(rhs);
544 if unlikely!(b) {None} else {Some(a)}
547 /// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
552 /// This results in undefined behavior when
553 #[doc = concat!("`self * rhs > ", stringify!($SelfT), "::MAX` or `self * rhs < ", stringify!($SelfT), "::MIN`,")]
554 /// i.e. when [`checked_mul`] would return `None`.
556 #[doc = concat!("[`checked_mul`]: ", stringify!($SelfT), "::checked_mul")]
558 feature = "unchecked_math",
559 reason = "niche optimization path",
562 #[must_use = "this returns the result of the operation, \
563 without modifying the original"]
564 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
566 pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
567 // SAFETY: the caller must uphold the safety contract for
569 unsafe { intrinsics::unchecked_mul(self, rhs) }
572 /// Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
573 /// or the division results in overflow.
580 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 1).checked_div(-1), Some(", stringify!($Max), "));")]
581 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_div(-1), None);")]
582 #[doc = concat!("assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);")]
584 #[stable(feature = "rust1", since = "1.0.0")]
585 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.52.0")]
586 #[must_use = "this returns the result of the operation, \
587 without modifying the original"]
589 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
590 if unlikely!(rhs == 0 || (self == Self::MIN && rhs == -1)) {
593 // SAFETY: div by zero and by INT_MIN have been checked above
594 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
598 /// Checked Euclidean division. Computes `self.div_euclid(rhs)`,
599 /// returning `None` if `rhs == 0` or the division results in overflow.
606 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 1).checked_div_euclid(-1), Some(", stringify!($Max), "));")]
607 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_div_euclid(-1), None);")]
608 #[doc = concat!("assert_eq!((1", stringify!($SelfT), ").checked_div_euclid(0), None);")]
610 #[stable(feature = "euclidean_division", since = "1.38.0")]
611 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
612 #[must_use = "this returns the result of the operation, \
613 without modifying the original"]
615 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
616 if unlikely!(rhs == 0 || (self == Self::MIN && rhs == -1)) {
619 Some(self.div_euclid(rhs))
623 /// Checked integer remainder. Computes `self % rhs`, returning `None` if
624 /// `rhs == 0` or the division results in overflow.
632 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));")]
633 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);")]
634 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);")]
636 #[stable(feature = "wrapping", since = "1.7.0")]
637 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.52.0")]
638 #[must_use = "this returns the result of the operation, \
639 without modifying the original"]
641 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
642 if unlikely!(rhs == 0 || (self == Self::MIN && rhs == -1)) {
645 // SAFETY: div by zero and by INT_MIN have been checked above
646 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
650 /// Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`
651 /// if `rhs == 0` or the division results in overflow.
658 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));")]
659 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);")]
660 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_rem_euclid(-1), None);")]
662 #[stable(feature = "euclidean_division", since = "1.38.0")]
663 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
664 #[must_use = "this returns the result of the operation, \
665 without modifying the original"]
667 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
668 if unlikely!(rhs == 0 || (self == Self::MIN && rhs == -1)) {
671 Some(self.rem_euclid(rhs))
675 /// Checked negation. Computes `-self`, returning `None` if `self == MIN`.
683 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));")]
684 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);")]
686 #[stable(feature = "wrapping", since = "1.7.0")]
687 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
689 pub const fn checked_neg(self) -> Option<Self> {
690 let (a, b) = self.overflowing_neg();
691 if unlikely!(b) {None} else {Some(a)}
694 /// Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
695 /// than or equal to the number of bits in `self`.
702 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));")]
703 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);")]
705 #[stable(feature = "wrapping", since = "1.7.0")]
706 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
707 #[must_use = "this returns the result of the operation, \
708 without modifying the original"]
710 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
711 let (a, b) = self.overflowing_shl(rhs);
712 if unlikely!(b) {None} else {Some(a)}
715 /// Unchecked shift left. Computes `self << rhs`, assuming that
716 /// `rhs` is less than the number of bits in `self`.
720 /// This results in undefined behavior if `rhs` is larger than
721 /// or equal to the number of bits in `self`,
722 /// i.e. when [`checked_shl`] would return `None`.
724 #[doc = concat!("[`checked_shl`]: ", stringify!($SelfT), "::checked_shl")]
726 feature = "unchecked_math",
727 reason = "niche optimization path",
730 #[must_use = "this returns the result of the operation, \
731 without modifying the original"]
732 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
734 pub const unsafe fn unchecked_shl(self, rhs: Self) -> Self {
735 // SAFETY: the caller must uphold the safety contract for
737 unsafe { intrinsics::unchecked_shl(self, rhs) }
740 /// Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
741 /// larger than or equal to the number of bits in `self`.
748 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));")]
749 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);")]
751 #[stable(feature = "wrapping", since = "1.7.0")]
752 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
753 #[must_use = "this returns the result of the operation, \
754 without modifying the original"]
756 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
757 let (a, b) = self.overflowing_shr(rhs);
758 if unlikely!(b) {None} else {Some(a)}
761 /// Unchecked shift right. Computes `self >> rhs`, assuming that
762 /// `rhs` is less than the number of bits in `self`.
766 /// This results in undefined behavior if `rhs` is larger than
767 /// or equal to the number of bits in `self`,
768 /// i.e. when [`checked_shr`] would return `None`.
770 #[doc = concat!("[`checked_shr`]: ", stringify!($SelfT), "::checked_shr")]
772 feature = "unchecked_math",
773 reason = "niche optimization path",
776 #[must_use = "this returns the result of the operation, \
777 without modifying the original"]
778 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
780 pub const unsafe fn unchecked_shr(self, rhs: Self) -> Self {
781 // SAFETY: the caller must uphold the safety contract for
783 unsafe { intrinsics::unchecked_shr(self, rhs) }
786 /// Checked absolute value. Computes `self.abs()`, returning `None` if
795 #[doc = concat!("assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));")]
796 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);")]
798 #[stable(feature = "no_panic_abs", since = "1.13.0")]
799 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
801 pub const fn checked_abs(self) -> Option<Self> {
802 if self.is_negative() {
809 /// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
810 /// overflow occurred.
817 #[doc = concat!("assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));")]
818 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);")]
821 #[stable(feature = "no_panic_pow", since = "1.34.0")]
822 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
823 #[must_use = "this returns the result of the operation, \
824 without modifying the original"]
826 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
831 let mut acc: Self = 1;
835 acc = try_opt!(acc.checked_mul(base));
838 base = try_opt!(base.checked_mul(base));
840 // since exp!=0, finally the exp must be 1.
841 // Deal with the final bit of the exponent separately, since
842 // squaring the base afterwards is not necessary and may cause a
843 // needless overflow.
844 Some(try_opt!(acc.checked_mul(base)))
847 /// Saturating integer addition. Computes `self + rhs`, saturating at the numeric
848 /// bounds instead of overflowing.
855 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);")]
856 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(100), ", stringify!($SelfT), "::MAX);")]
857 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_add(-1), ", stringify!($SelfT), "::MIN);")]
860 #[stable(feature = "rust1", since = "1.0.0")]
861 #[rustc_const_stable(feature = "const_saturating_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 saturating_add(self, rhs: Self) -> Self {
866 intrinsics::saturating_add(self, rhs)
869 /// Saturating addition with an unsigned integer. Computes `self + rhs`,
870 /// saturating at the numeric bounds instead of overflowing.
877 /// # #![feature(mixed_integer_ops)]
878 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_unsigned(2), 3);")]
879 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add_unsigned(100), ", stringify!($SelfT), "::MAX);")]
881 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
882 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
883 #[must_use = "this returns the result of the operation, \
884 without modifying the original"]
886 pub const fn saturating_add_unsigned(self, rhs: $UnsignedT) -> Self {
887 // Overflow can only happen at the upper bound
888 self.checked_add_unsigned(rhs).unwrap_or(Self::MAX)
891 /// Saturating integer subtraction. Computes `self - rhs`, saturating at the
892 /// numeric bounds instead of overflowing.
899 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);")]
900 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_sub(100), ", stringify!($SelfT), "::MIN);")]
901 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_sub(-1), ", stringify!($SelfT), "::MAX);")]
903 #[stable(feature = "rust1", since = "1.0.0")]
904 #[rustc_const_stable(feature = "const_saturating_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 saturating_sub(self, rhs: Self) -> Self {
909 intrinsics::saturating_sub(self, rhs)
912 /// Saturating subtraction with an unsigned integer. Computes `self - rhs`,
913 /// saturating at the numeric bounds instead of overflowing.
920 /// # #![feature(mixed_integer_ops)]
921 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_sub_unsigned(127), -27);")]
922 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_sub_unsigned(100), ", stringify!($SelfT), "::MIN);")]
924 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
925 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
926 #[must_use = "this returns the result of the operation, \
927 without modifying the original"]
929 pub const fn saturating_sub_unsigned(self, rhs: $UnsignedT) -> Self {
930 // Overflow can only happen at the lower bound
931 self.checked_sub_unsigned(rhs).unwrap_or(Self::MIN)
934 /// Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
935 /// instead of overflowing.
942 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_neg(), -100);")]
943 #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").saturating_neg(), 100);")]
944 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_neg(), ", stringify!($SelfT), "::MAX);")]
945 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_neg(), ", stringify!($SelfT), "::MIN + 1);")]
948 #[stable(feature = "saturating_neg", since = "1.45.0")]
949 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
951 pub const fn saturating_neg(self) -> Self {
952 intrinsics::saturating_sub(0, self)
955 /// Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
956 /// MIN` instead of overflowing.
963 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_abs(), 100);")]
964 #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").saturating_abs(), 100);")]
965 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_abs(), ", stringify!($SelfT), "::MAX);")]
966 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 1).saturating_abs(), ", stringify!($SelfT), "::MAX);")]
969 #[stable(feature = "saturating_neg", since = "1.45.0")]
970 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
972 pub const fn saturating_abs(self) -> Self {
973 if self.is_negative() {
974 self.saturating_neg()
980 /// Saturating integer multiplication. Computes `self * rhs`, saturating at the
981 /// numeric bounds instead of overflowing.
989 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);")]
990 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);")]
991 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);")]
993 #[stable(feature = "wrapping", since = "1.7.0")]
994 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
995 #[must_use = "this returns the result of the operation, \
996 without modifying the original"]
998 pub const fn saturating_mul(self, rhs: Self) -> Self {
999 match self.checked_mul(rhs) {
1001 None => if (self < 0) == (rhs < 0) {
1009 /// Saturating integer division. Computes `self / rhs`, saturating at the
1010 /// numeric bounds instead of overflowing.
1017 /// #![feature(saturating_div)]
1019 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".saturating_div(2), 2);")]
1020 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_div(-1), ", stringify!($SelfT), "::MIN + 1);")]
1021 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_div(-1), ", stringify!($SelfT), "::MAX);")]
1026 /// #![feature(saturating_div)]
1028 #[doc = concat!("let _ = 1", stringify!($SelfT), ".saturating_div(0);")]
1031 #[unstable(feature = "saturating_div", issue = "87920")]
1032 #[rustc_const_unstable(feature = "saturating_div", issue = "87920")]
1033 #[must_use = "this returns the result of the operation, \
1034 without modifying the original"]
1036 pub const fn saturating_div(self, rhs: Self) -> Self {
1037 match self.overflowing_div(rhs) {
1038 (result, false) => result,
1039 (_result, true) => Self::MAX, // MIN / -1 is the only possible saturating overflow
1043 /// Saturating integer exponentiation. Computes `self.pow(exp)`,
1044 /// saturating at the numeric bounds instead of overflowing.
1052 #[doc = concat!("assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);")]
1053 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);")]
1054 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);")]
1056 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1057 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1058 #[must_use = "this returns the result of the operation, \
1059 without modifying the original"]
1061 pub const fn saturating_pow(self, exp: u32) -> Self {
1062 match self.checked_pow(exp) {
1064 None if self < 0 && exp % 2 == 1 => Self::MIN,
1069 /// Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
1070 /// boundary of the type.
1077 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);")]
1078 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_add(2), ", stringify!($SelfT), "::MIN + 1);")]
1080 #[stable(feature = "rust1", since = "1.0.0")]
1081 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1082 #[must_use = "this returns the result of the operation, \
1083 without modifying the original"]
1085 pub const fn wrapping_add(self, rhs: Self) -> Self {
1086 intrinsics::wrapping_add(self, rhs)
1089 /// Wrapping (modular) addition with an unsigned integer. Computes
1090 /// `self + rhs`, wrapping around at the boundary of the type.
1097 /// # #![feature(mixed_integer_ops)]
1098 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_add_unsigned(27), 127);")]
1099 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_add_unsigned(2), ", stringify!($SelfT), "::MIN + 1);")]
1101 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1102 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1103 #[must_use = "this returns the result of the operation, \
1104 without modifying the original"]
1106 pub const fn wrapping_add_unsigned(self, rhs: $UnsignedT) -> Self {
1107 self.wrapping_add(rhs as Self)
1110 /// Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1111 /// boundary of the type.
1118 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);")]
1119 #[doc = concat!("assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::MAX), ", stringify!($SelfT), "::MAX);")]
1121 #[stable(feature = "rust1", since = "1.0.0")]
1122 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1123 #[must_use = "this returns the result of the operation, \
1124 without modifying the original"]
1126 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1127 intrinsics::wrapping_sub(self, rhs)
1130 /// Wrapping (modular) subtraction with an unsigned integer. Computes
1131 /// `self - rhs`, wrapping around at the boundary of the type.
1138 /// # #![feature(mixed_integer_ops)]
1139 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".wrapping_sub_unsigned(127), -127);")]
1140 #[doc = concat!("assert_eq!((-2", stringify!($SelfT), ").wrapping_sub_unsigned(", stringify!($UnsignedT), "::MAX), -1);")]
1142 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1143 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1144 #[must_use = "this returns the result of the operation, \
1145 without modifying the original"]
1147 pub const fn wrapping_sub_unsigned(self, rhs: $UnsignedT) -> Self {
1148 self.wrapping_sub(rhs as Self)
1151 /// Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1152 /// the boundary of the type.
1159 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);")]
1160 /// assert_eq!(11i8.wrapping_mul(12), -124);
1162 #[stable(feature = "rust1", since = "1.0.0")]
1163 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1164 #[must_use = "this returns the result of the operation, \
1165 without modifying the original"]
1167 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1168 intrinsics::wrapping_mul(self, rhs)
1171 /// Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1172 /// boundary of the type.
1174 /// The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1175 /// `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1176 /// that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1180 /// This function will panic if `rhs` is 0.
1187 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);")]
1188 /// assert_eq!((-128i8).wrapping_div(-1), -128);
1190 #[stable(feature = "num_wrapping", since = "1.2.0")]
1191 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1192 #[must_use = "this returns the result of the operation, \
1193 without modifying the original"]
1195 pub const fn wrapping_div(self, rhs: Self) -> Self {
1196 self.overflowing_div(rhs).0
1199 /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
1200 /// wrapping around at the boundary of the type.
1202 /// Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1203 /// for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1204 /// type. In this case, this method returns `MIN` itself.
1208 /// This function will panic if `rhs` is 0.
1215 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);")]
1216 /// assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
1218 #[stable(feature = "euclidean_division", since = "1.38.0")]
1219 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1220 #[must_use = "this returns the result of the operation, \
1221 without modifying the original"]
1223 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
1224 self.overflowing_div_euclid(rhs).0
1227 /// Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1228 /// boundary of the type.
1230 /// Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1231 /// invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1232 /// this function returns `0`.
1236 /// This function will panic if `rhs` is 0.
1243 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);")]
1244 /// assert_eq!((-128i8).wrapping_rem(-1), 0);
1246 #[stable(feature = "num_wrapping", since = "1.2.0")]
1247 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1248 #[must_use = "this returns the result of the operation, \
1249 without modifying the original"]
1251 pub const fn wrapping_rem(self, rhs: Self) -> Self {
1252 self.overflowing_rem(rhs).0
1255 /// Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
1256 /// at the boundary of the type.
1258 /// Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1259 /// for the type). In this case, this method returns 0.
1263 /// This function will panic if `rhs` is 0.
1270 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);")]
1271 /// assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
1273 #[stable(feature = "euclidean_division", since = "1.38.0")]
1274 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1275 #[must_use = "this returns the result of the operation, \
1276 without modifying the original"]
1278 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1279 self.overflowing_rem_euclid(rhs).0
1282 /// Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1285 /// The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1286 /// is the negative minimal value for the type); this is a positive value that is too large to represent
1287 /// in the type. In such a case, this function returns `MIN` itself.
1294 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);")]
1295 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.wrapping_neg(), ", stringify!($SelfT), "::MIN);")]
1297 #[stable(feature = "num_wrapping", since = "1.2.0")]
1298 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1300 pub const fn wrapping_neg(self) -> Self {
1301 (0 as $SelfT).wrapping_sub(self)
1304 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1305 /// any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1307 /// Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1308 /// the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1309 /// The primitive integer types all implement a [`rotate_left`](Self::rotate_left) function,
1310 /// which may be what you want instead.
1317 #[doc = concat!("assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);")]
1318 #[doc = concat!("assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);")]
1320 #[stable(feature = "num_wrapping", since = "1.2.0")]
1321 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1322 #[must_use = "this returns the result of the operation, \
1323 without modifying the original"]
1325 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1326 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1329 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1333 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1334 /// removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1336 /// Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1337 /// to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1338 /// end. The primitive integer types all implement a [`rotate_right`](Self::rotate_right) function,
1339 /// which may be what you want instead.
1346 #[doc = concat!("assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);")]
1347 /// assert_eq!((-128i16).wrapping_shr(64), -128);
1349 #[stable(feature = "num_wrapping", since = "1.2.0")]
1350 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1351 #[must_use = "this returns the result of the operation, \
1352 without modifying the original"]
1354 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1355 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1358 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1362 /// Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1363 /// the boundary of the type.
1365 /// The only case where such wrapping can occur is when one takes the absolute value of the negative
1366 /// minimal value for the type; this is a positive value that is too large to represent in the type. In
1367 /// such a case, this function returns `MIN` itself.
1374 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);")]
1375 #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);")]
1376 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.wrapping_abs(), ", stringify!($SelfT), "::MIN);")]
1377 /// assert_eq!((-128i8).wrapping_abs() as u8, 128);
1379 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1380 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1381 #[allow(unused_attributes)]
1383 pub const fn wrapping_abs(self) -> Self {
1384 if self.is_negative() {
1391 /// Computes the absolute value of `self` without any wrapping
1400 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".unsigned_abs(), 100", stringify!($UnsignedT), ");")]
1401 #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").unsigned_abs(), 100", stringify!($UnsignedT), ");")]
1402 /// assert_eq!((-128i8).unsigned_abs(), 128u8);
1404 #[stable(feature = "unsigned_abs", since = "1.51.0")]
1405 #[rustc_const_stable(feature = "unsigned_abs", since = "1.51.0")]
1407 pub const fn unsigned_abs(self) -> $UnsignedT {
1408 self.wrapping_abs() as $UnsignedT
1411 /// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1412 /// wrapping around at the boundary of the type.
1419 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);")]
1420 /// assert_eq!(3i8.wrapping_pow(5), -13);
1421 /// assert_eq!(3i8.wrapping_pow(6), -39);
1423 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1424 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1425 #[must_use = "this returns the result of the operation, \
1426 without modifying the original"]
1428 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
1432 let mut base = self;
1433 let mut acc: Self = 1;
1437 acc = acc.wrapping_mul(base);
1440 base = base.wrapping_mul(base);
1443 // since exp!=0, finally the exp must be 1.
1444 // Deal with the final bit of the exponent separately, since
1445 // squaring the base afterwards is not necessary and may cause a
1446 // needless overflow.
1447 acc.wrapping_mul(base)
1450 /// Calculates `self` + `rhs`
1452 /// Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1453 /// occur. If an overflow would have occurred then the wrapped value is returned.
1461 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));")]
1462 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT), "::MIN, true));")]
1464 #[stable(feature = "wrapping", since = "1.7.0")]
1465 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1466 #[must_use = "this returns the result of the operation, \
1467 without modifying the original"]
1469 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1470 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1474 /// Calculates `self + rhs + carry` without the ability to overflow.
1476 /// Performs "ternary addition" which takes in an extra bit to add, and may return an
1477 /// additional bit of overflow. This allows for chaining together multiple additions
1478 /// to create "big integers" which represent larger values.
1485 /// #![feature(bigint_helper_methods)]
1486 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".carrying_add(2, false), (7, false));")]
1487 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".carrying_add(2, true), (8, false));")]
1488 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.carrying_add(1, false), (", stringify!($SelfT), "::MIN, false));")]
1489 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.carrying_add(1, true), (", stringify!($SelfT), "::MIN + 1, false));")]
1491 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
1492 #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")]
1493 #[must_use = "this returns the result of the operation, \
1494 without modifying the original"]
1496 pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
1497 let (sum, carry) = (self as $UnsignedT).carrying_add(rhs as $UnsignedT, carry);
1498 (sum as $SelfT, carry)
1501 /// Calculates `self` + `rhs` with an unsigned `rhs`
1503 /// Returns a tuple of the addition along with a boolean indicating
1504 /// whether an arithmetic overflow would occur. If an overflow would
1505 /// have occurred then the wrapped value is returned.
1512 /// # #![feature(mixed_integer_ops)]
1513 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_unsigned(2), (3, false));")]
1514 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN).overflowing_add_unsigned(", stringify!($UnsignedT), "::MAX), (", stringify!($SelfT), "::MAX, false));")]
1515 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).overflowing_add_unsigned(3), (", stringify!($SelfT), "::MIN, true));")]
1517 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1518 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1519 #[must_use = "this returns the result of the operation, \
1520 without modifying the original"]
1522 pub const fn overflowing_add_unsigned(self, rhs: $UnsignedT) -> (Self, bool) {
1523 let rhs = rhs as Self;
1524 let (res, overflowed) = self.overflowing_add(rhs);
1525 (res, overflowed ^ (rhs < 0))
1528 /// Calculates `self` - `rhs`
1530 /// Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1531 /// would occur. If an overflow would have occurred then the wrapped value is returned.
1539 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));")]
1540 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")]
1542 #[stable(feature = "wrapping", since = "1.7.0")]
1543 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1544 #[must_use = "this returns the result of the operation, \
1545 without modifying the original"]
1547 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1548 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1552 /// Calculates `self - rhs - borrow` without the ability to overflow.
1554 /// Performs "ternary subtraction" which takes in an extra bit to subtract, and may return
1555 /// an additional bit of overflow. This allows for chaining together multiple subtractions
1556 /// to create "big integers" which represent larger values.
1563 /// #![feature(bigint_helper_methods)]
1564 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".borrowing_sub(2, false), (3, false));")]
1565 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".borrowing_sub(2, true), (2, false));")]
1566 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.borrowing_sub(1, false), (", stringify!($SelfT), "::MAX, false));")]
1567 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.borrowing_sub(1, true), (", stringify!($SelfT), "::MAX - 1, false));")]
1569 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
1570 #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")]
1571 #[must_use = "this returns the result of the operation, \
1572 without modifying the original"]
1574 pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
1575 let (sum, borrow) = (self as $UnsignedT).borrowing_sub(rhs as $UnsignedT, borrow);
1576 (sum as $SelfT, borrow)
1579 /// Calculates `self` - `rhs` with an unsigned `rhs`
1581 /// Returns a tuple of the subtraction along with a boolean indicating
1582 /// whether an arithmetic overflow would occur. If an overflow would
1583 /// have occurred then the wrapped value is returned.
1590 /// # #![feature(mixed_integer_ops)]
1591 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_sub_unsigned(2), (-1, false));")]
1592 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX).overflowing_sub_unsigned(", stringify!($UnsignedT), "::MAX), (", stringify!($SelfT), "::MIN, false));")]
1593 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 2).overflowing_sub_unsigned(3), (", stringify!($SelfT), "::MAX, true));")]
1595 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1596 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1597 #[must_use = "this returns the result of the operation, \
1598 without modifying the original"]
1600 pub const fn overflowing_sub_unsigned(self, rhs: $UnsignedT) -> (Self, bool) {
1601 let rhs = rhs as Self;
1602 let (res, overflowed) = self.overflowing_sub(rhs);
1603 (res, overflowed ^ (rhs < 0))
1606 /// Calculates the multiplication of `self` and `rhs`.
1608 /// Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1609 /// would occur. If an overflow would have occurred then the wrapped value is returned.
1616 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));")]
1617 /// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
1619 #[stable(feature = "wrapping", since = "1.7.0")]
1620 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1621 #[must_use = "this returns the result of the operation, \
1622 without modifying the original"]
1624 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1625 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1629 /// Calculates the divisor when `self` is divided by `rhs`.
1631 /// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1632 /// occur. If an overflow would occur then self is returned.
1636 /// This function will panic if `rhs` is 0.
1644 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));")]
1645 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT), "::MIN, true));")]
1648 #[stable(feature = "wrapping", since = "1.7.0")]
1649 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1650 #[must_use = "this returns the result of the operation, \
1651 without modifying the original"]
1652 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1653 if unlikely!(self == Self::MIN && rhs == -1) {
1660 /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1662 /// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1663 /// occur. If an overflow would occur then `self` is returned.
1667 /// This function will panic if `rhs` is 0.
1674 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));")]
1675 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euclid(-1), (", stringify!($SelfT), "::MIN, true));")]
1678 #[stable(feature = "euclidean_division", since = "1.38.0")]
1679 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1680 #[must_use = "this returns the result of the operation, \
1681 without modifying the original"]
1682 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1683 if unlikely!(self == Self::MIN && rhs == -1) {
1686 (self.div_euclid(rhs), false)
1690 /// Calculates the remainder when `self` is divided by `rhs`.
1692 /// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1693 /// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1697 /// This function will panic if `rhs` is 0.
1705 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));")]
1706 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));")]
1709 #[stable(feature = "wrapping", since = "1.7.0")]
1710 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1711 #[must_use = "this returns the result of the operation, \
1712 without modifying the original"]
1713 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1714 if unlikely!(self == Self::MIN && rhs == -1) {
1722 /// Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
1724 /// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1725 /// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1729 /// This function will panic if `rhs` is 0.
1736 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));")]
1737 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem_euclid(-1), (0, true));")]
1739 #[stable(feature = "euclidean_division", since = "1.38.0")]
1740 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1741 #[must_use = "this returns the result of the operation, \
1742 without modifying the original"]
1744 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1745 if unlikely!(self == Self::MIN && rhs == -1) {
1748 (self.rem_euclid(rhs), false)
1753 /// Negates self, overflowing if this is equal to the minimum value.
1755 /// Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1756 /// happened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the
1757 /// minimum value will be returned again and `true` will be returned for an overflow happening.
1764 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));")]
1765 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT), "::MIN, true));")]
1768 #[stable(feature = "wrapping", since = "1.7.0")]
1769 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1770 #[allow(unused_attributes)]
1771 pub const fn overflowing_neg(self) -> (Self, bool) {
1772 if unlikely!(self == Self::MIN) {
1779 /// Shifts self left by `rhs` bits.
1781 /// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1782 /// value was larger than or equal to the number of bits. If the shift value is too large, then value is
1783 /// masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1790 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));")]
1791 /// assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));
1793 #[stable(feature = "wrapping", since = "1.7.0")]
1794 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1795 #[must_use = "this returns the result of the operation, \
1796 without modifying the original"]
1798 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1799 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1802 /// Shifts self right by `rhs` bits.
1804 /// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1805 /// value was larger than or equal to the number of bits. If the shift value is too large, then value is
1806 /// masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1813 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));")]
1814 /// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
1816 #[stable(feature = "wrapping", since = "1.7.0")]
1817 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1818 #[must_use = "this returns the result of the operation, \
1819 without modifying the original"]
1821 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1822 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1825 /// Computes the absolute value of `self`.
1827 /// Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1828 /// happened. If self is the minimum value
1829 #[doc = concat!("(e.g., ", stringify!($SelfT), "::MIN for values of type ", stringify!($SelfT), "),")]
1830 /// then the minimum value will be returned again and true will be returned
1831 /// for an overflow happening.
1838 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));")]
1839 #[doc = concat!("assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));")]
1840 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN).overflowing_abs(), (", stringify!($SelfT), "::MIN, true));")]
1842 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1843 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1845 pub const fn overflowing_abs(self) -> (Self, bool) {
1846 (self.wrapping_abs(), self == Self::MIN)
1849 /// Raises self to the power of `exp`, using exponentiation by squaring.
1851 /// Returns a tuple of the exponentiation along with a bool indicating
1852 /// whether an overflow happened.
1859 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));")]
1860 /// assert_eq!(3i8.overflowing_pow(5), (-13, true));
1862 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1863 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1864 #[must_use = "this returns the result of the operation, \
1865 without modifying the original"]
1867 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1871 let mut base = self;
1872 let mut acc: Self = 1;
1873 let mut overflown = false;
1874 // Scratch space for storing results of overflowing_mul.
1879 r = acc.overflowing_mul(base);
1884 r = base.overflowing_mul(base);
1889 // since exp!=0, finally the exp must be 1.
1890 // Deal with the final bit of the exponent separately, since
1891 // squaring the base afterwards is not necessary and may cause a
1892 // needless overflow.
1893 r = acc.overflowing_mul(base);
1898 /// Raises self to the power of `exp`, using exponentiation by squaring.
1905 #[doc = concat!("let x: ", stringify!($SelfT), " = 2; // or any other integer type")]
1907 /// assert_eq!(x.pow(5), 32);
1909 #[stable(feature = "rust1", since = "1.0.0")]
1910 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1911 #[must_use = "this returns the result of the operation, \
1912 without modifying the original"]
1914 #[rustc_inherit_overflow_checks]
1915 pub const fn pow(self, mut exp: u32) -> Self {
1919 let mut base = self;
1930 // since exp!=0, finally the exp must be 1.
1931 // Deal with the final bit of the exponent separately, since
1932 // squaring the base afterwards is not necessary and may cause a
1933 // needless overflow.
1937 /// Calculates the quotient of Euclidean division of `self` by `rhs`.
1939 /// This computes the integer `q` such that `self = q * rhs + r`, with
1940 /// `r = self.rem_euclid(rhs)` and `0 <= r < abs(rhs)`.
1942 /// In other words, the result is `self / rhs` rounded to the integer `q`
1943 /// such that `self >= q * rhs`.
1944 /// If `self > 0`, this is equal to round towards zero (the default in Rust);
1945 /// if `self < 0`, this is equal to round towards +/- infinity.
1949 /// This function will panic if `rhs` is 0 or the division results in overflow.
1956 #[doc = concat!("let a: ", stringify!($SelfT), " = 7; // or any other integer type")]
1959 /// assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
1960 /// assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
1961 /// assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
1962 /// assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
1964 #[stable(feature = "euclidean_division", since = "1.38.0")]
1965 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1966 #[must_use = "this returns the result of the operation, \
1967 without modifying the original"]
1969 #[rustc_inherit_overflow_checks]
1970 pub const fn div_euclid(self, rhs: Self) -> Self {
1973 return if rhs > 0 { q - 1 } else { q + 1 }
1979 /// Calculates the least nonnegative remainder of `self (mod rhs)`.
1981 /// This is done as if by the Euclidean division algorithm -- given
1982 /// `r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) + r`, and
1983 /// `0 <= r < abs(rhs)`.
1987 /// This function will panic if `rhs` is 0 or the division results in overflow.
1994 #[doc = concat!("let a: ", stringify!($SelfT), " = 7; // or any other integer type")]
1997 /// assert_eq!(a.rem_euclid(b), 3);
1998 /// assert_eq!((-a).rem_euclid(b), 1);
1999 /// assert_eq!(a.rem_euclid(-b), 3);
2000 /// assert_eq!((-a).rem_euclid(-b), 1);
2002 #[stable(feature = "euclidean_division", since = "1.38.0")]
2003 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
2004 #[must_use = "this returns the result of the operation, \
2005 without modifying the original"]
2007 #[rustc_inherit_overflow_checks]
2008 pub const fn rem_euclid(self, rhs: Self) -> Self {
2021 /// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
2025 /// This function will panic if `rhs` is 0 or the division results in overflow.
2032 /// #![feature(int_roundings)]
2033 #[doc = concat!("let a: ", stringify!($SelfT)," = 8;")]
2036 /// assert_eq!(a.unstable_div_floor(b), 2);
2037 /// assert_eq!(a.unstable_div_floor(-b), -3);
2038 /// assert_eq!((-a).unstable_div_floor(b), -3);
2039 /// assert_eq!((-a).unstable_div_floor(-b), 2);
2041 #[unstable(feature = "int_roundings", issue = "88581")]
2042 #[must_use = "this returns the result of the operation, \
2043 without modifying the original"]
2045 #[rustc_inherit_overflow_checks]
2046 pub const fn unstable_div_floor(self, rhs: Self) -> Self {
2049 if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) {
2056 /// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
2060 /// This function will panic if `rhs` is 0 or the division results in overflow.
2067 /// #![feature(int_roundings)]
2068 #[doc = concat!("let a: ", stringify!($SelfT)," = 8;")]
2071 /// assert_eq!(a.unstable_div_ceil(b), 3);
2072 /// assert_eq!(a.unstable_div_ceil(-b), -2);
2073 /// assert_eq!((-a).unstable_div_ceil(b), -2);
2074 /// assert_eq!((-a).unstable_div_ceil(-b), 3);
2076 #[unstable(feature = "int_roundings", issue = "88581")]
2077 #[must_use = "this returns the result of the operation, \
2078 without modifying the original"]
2080 #[rustc_inherit_overflow_checks]
2081 pub const fn unstable_div_ceil(self, rhs: Self) -> Self {
2084 if (r > 0 && rhs > 0) || (r < 0 && rhs < 0) {
2091 /// If `rhs` is positive, calculates the smallest value greater than or
2092 /// equal to `self` that is a multiple of `rhs`. If `rhs` is negative,
2093 /// calculates the largest value less than or equal to `self` that is a
2094 /// multiple of `rhs`.
2098 /// This function will panic if `rhs` is 0 or the operation results in overflow.
2105 /// #![feature(int_roundings)]
2106 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".unstable_next_multiple_of(8), 16);")]
2107 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".unstable_next_multiple_of(8), 24);")]
2108 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".unstable_next_multiple_of(-8), 16);")]
2109 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".unstable_next_multiple_of(-8), 16);")]
2110 #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").unstable_next_multiple_of(8), -16);")]
2111 #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").unstable_next_multiple_of(8), -16);")]
2112 #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").unstable_next_multiple_of(-8), -16);")]
2113 #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").unstable_next_multiple_of(-8), -24);")]
2115 #[unstable(feature = "int_roundings", issue = "88581")]
2116 #[must_use = "this returns the result of the operation, \
2117 without modifying the original"]
2119 #[rustc_inherit_overflow_checks]
2120 pub const fn unstable_next_multiple_of(self, rhs: Self) -> Self {
2121 // This would otherwise fail when calculating `r` when self == T::MIN.
2127 let m = if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) {
2140 /// If `rhs` is positive, calculates the smallest value greater than or
2141 /// equal to `self` that is a multiple of `rhs`. If `rhs` is negative,
2142 /// calculates the largest value less than or equal to `self` that is a
2143 /// multiple of `rhs`. Returns `None` if `rhs` is zero or the operation
2144 /// would result in overflow.
2151 /// #![feature(int_roundings)]
2152 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(16));")]
2153 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(24));")]
2154 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(-8), Some(16));")]
2155 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(-8), Some(16));")]
2156 #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").checked_next_multiple_of(8), Some(-16));")]
2157 #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").checked_next_multiple_of(8), Some(-16));")]
2158 #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").checked_next_multiple_of(-8), Some(-16));")]
2159 #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").checked_next_multiple_of(-8), Some(-24));")]
2160 #[doc = concat!("assert_eq!(1_", stringify!($SelfT), ".checked_next_multiple_of(0), None);")]
2161 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_multiple_of(2), None);")]
2163 #[unstable(feature = "int_roundings", issue = "88581")]
2164 #[must_use = "this returns the result of the operation, \
2165 without modifying the original"]
2167 #[rustc_inherit_overflow_checks]
2168 pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
2169 // This would otherwise fail when calculating `r` when self == T::MIN.
2174 let r = try_opt!(self.checked_rem(rhs));
2175 let m = if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) {
2176 try_opt!(r.checked_add(rhs))
2184 self.checked_add(try_opt!(rhs.checked_sub(m)))
2188 /// Returns the logarithm of the number with respect to an arbitrary base.
2190 /// This method might not be optimized owing to implementation details;
2191 /// `log2` can produce results more efficiently for base 2, and `log10`
2192 /// can produce results more efficiently for base 10.
2196 /// When the number is zero, or if the base is not at least 2; it
2197 /// panics in debug mode and the return value is wrapped to 0 in release
2198 /// mode (the only situation in which the method can return 0).
2203 /// #![feature(int_log)]
2204 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".log(5), 1);")]
2206 #[unstable(feature = "int_log", issue = "70887")]
2207 #[must_use = "this returns the result of the operation, \
2208 without modifying the original"]
2211 #[rustc_inherit_overflow_checks]
2212 #[allow(arithmetic_overflow)]
2213 pub const fn log(self, base: Self) -> u32 {
2214 match self.checked_log(base) {
2217 // In debug builds, trigger a panic on None.
2218 // This should optimize completely out in release builds.
2219 let _ = Self::MAX + 1;
2226 /// Returns the base 2 logarithm of the number.
2230 /// When the number is zero it panics in debug mode and the return value
2231 /// is wrapped to 0 in release mode (the only situation in which the
2232 /// method can return 0).
2237 /// #![feature(int_log)]
2238 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".log2(), 1);")]
2240 #[unstable(feature = "int_log", issue = "70887")]
2241 #[must_use = "this returns the result of the operation, \
2242 without modifying the original"]
2245 #[rustc_inherit_overflow_checks]
2246 #[allow(arithmetic_overflow)]
2247 pub const fn log2(self) -> u32 {
2248 match self.checked_log2() {
2251 // In debug builds, trigger a panic on None.
2252 // This should optimize completely out in release builds.
2253 let _ = Self::MAX + 1;
2260 /// Returns the base 10 logarithm of the number.
2264 /// When the number is zero it panics in debug mode and the return value
2265 /// is wrapped to 0 in release mode (the only situation in which the
2266 /// method can return 0).
2271 /// #![feature(int_log)]
2272 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".log10(), 1);")]
2274 #[unstable(feature = "int_log", issue = "70887")]
2275 #[must_use = "this returns the result of the operation, \
2276 without modifying the original"]
2279 #[rustc_inherit_overflow_checks]
2280 #[allow(arithmetic_overflow)]
2281 pub const fn log10(self) -> u32 {
2282 match self.checked_log10() {
2285 // In debug builds, trigger a panic on None.
2286 // This should optimize completely out in release builds.
2287 let _ = Self::MAX + 1;
2294 /// Returns the logarithm of the number with respect to an arbitrary base.
2296 /// Returns `None` if the number is negative or zero, or if the base is not at least 2.
2298 /// This method might not be optimized owing to implementation details;
2299 /// `checked_log2` can produce results more efficiently for base 2, and
2300 /// `checked_log10` can produce results more efficiently for base 10.
2305 /// #![feature(int_log)]
2306 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_log(5), Some(1));")]
2308 #[unstable(feature = "int_log", issue = "70887")]
2309 #[must_use = "this returns the result of the operation, \
2310 without modifying the original"]
2312 pub const fn checked_log(self, base: Self) -> Option<u32> {
2313 if self <= 0 || base <= 1 {
2319 // Optimization for 128 bit wide integers.
2320 if Self::BITS == 128 {
2321 let b = Self::log2(self) / (Self::log2(base) + 1);
2323 r /= base.pow(b as u32);
2334 /// Returns the base 2 logarithm of the number.
2336 /// Returns `None` if the number is negative or zero.
2341 /// #![feature(int_log)]
2342 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_log2(), Some(1));")]
2344 #[unstable(feature = "int_log", issue = "70887")]
2345 #[must_use = "this returns the result of the operation, \
2346 without modifying the original"]
2348 pub const fn checked_log2(self) -> Option<u32> {
2352 // SAFETY: We just checked that this number is positive
2353 let log = (Self::BITS - 1) - unsafe { intrinsics::ctlz_nonzero(self) as u32 };
2358 /// Returns the base 10 logarithm of the number.
2360 /// Returns `None` if the number is negative or zero.
2365 /// #![feature(int_log)]
2366 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_log10(), Some(1));")]
2368 #[unstable(feature = "int_log", issue = "70887")]
2369 #[must_use = "this returns the result of the operation, \
2370 without modifying the original"]
2372 pub const fn checked_log10(self) -> Option<u32> {
2373 int_log10::$ActualT(self as $ActualT)
2376 /// Computes the absolute value of `self`.
2378 /// # Overflow behavior
2380 /// The absolute value of
2381 #[doc = concat!("`", stringify!($SelfT), "::MIN`")]
2382 /// cannot be represented as an
2383 #[doc = concat!("`", stringify!($SelfT), "`,")]
2384 /// and attempting to calculate it will cause an overflow. This means
2385 /// that code in debug mode will trigger a panic on this case and
2386 /// optimized code will return
2387 #[doc = concat!("`", stringify!($SelfT), "::MIN`")]
2388 /// without a panic.
2395 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".abs(), 10);")]
2396 #[doc = concat!("assert_eq!((-10", stringify!($SelfT), ").abs(), 10);")]
2398 #[stable(feature = "rust1", since = "1.0.0")]
2399 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2400 #[allow(unused_attributes)]
2402 #[rustc_inherit_overflow_checks]
2403 pub const fn abs(self) -> Self {
2404 // Note that the #[rustc_inherit_overflow_checks] and #[inline]
2405 // above mean that the overflow semantics of the subtraction
2406 // depend on the crate we're being called from.
2407 if self.is_negative() {
2414 /// Returns a number representing sign of `self`.
2416 /// - `0` if the number is zero
2417 /// - `1` if the number is positive
2418 /// - `-1` if the number is negative
2425 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".signum(), 1);")]
2426 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".signum(), 0);")]
2427 #[doc = concat!("assert_eq!((-10", stringify!($SelfT), ").signum(), -1);")]
2429 #[stable(feature = "rust1", since = "1.0.0")]
2430 #[rustc_const_stable(feature = "const_int_sign", since = "1.47.0")]
2432 pub const fn signum(self) -> Self {
2440 /// Returns `true` if `self` is positive and `false` if the number is zero or
2448 #[doc = concat!("assert!(10", stringify!($SelfT), ".is_positive());")]
2449 #[doc = concat!("assert!(!(-10", stringify!($SelfT), ").is_positive());")]
2451 #[stable(feature = "rust1", since = "1.0.0")]
2452 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2454 pub const fn is_positive(self) -> bool { self > 0 }
2456 /// Returns `true` if `self` is negative and `false` if the number is zero or
2464 #[doc = concat!("assert!((-10", stringify!($SelfT), ").is_negative());")]
2465 #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_negative());")]
2467 #[stable(feature = "rust1", since = "1.0.0")]
2468 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2470 pub const fn is_negative(self) -> bool { self < 0 }
2472 /// Return the memory representation of this integer as a byte array in
2473 /// big-endian (network) byte order.
2475 #[doc = $to_xe_bytes_doc]
2480 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();")]
2481 #[doc = concat!("assert_eq!(bytes, ", $be_bytes, ");")]
2483 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2484 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2486 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2487 self.to_be().to_ne_bytes()
2490 /// Return the memory representation of this integer as a byte array in
2491 /// little-endian byte order.
2493 #[doc = $to_xe_bytes_doc]
2498 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();")]
2499 #[doc = concat!("assert_eq!(bytes, ", $le_bytes, ");")]
2501 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2502 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2504 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2505 self.to_le().to_ne_bytes()
2508 /// Return the memory representation of this integer as a byte array in
2509 /// native byte order.
2511 /// As the target platform's native endianness is used, portable code
2512 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2515 #[doc = $to_xe_bytes_doc]
2517 /// [`to_be_bytes`]: Self::to_be_bytes
2518 /// [`to_le_bytes`]: Self::to_le_bytes
2523 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();")]
2526 /// if cfg!(target_endian = "big") {
2527 #[doc = concat!(" ", $be_bytes)]
2529 #[doc = concat!(" ", $le_bytes)]
2533 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2534 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2535 // SAFETY: const sound because integers are plain old datatypes so we can always
2536 // transmute them to arrays of bytes
2538 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2539 // SAFETY: integers are plain old datatypes so we can always transmute them to
2541 unsafe { mem::transmute(self) }
2544 /// Create an integer value from its representation as a byte array in
2547 #[doc = $to_xe_bytes_doc]
2552 #[doc = concat!("let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");")]
2553 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2556 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2559 /// use std::convert::TryInto;
2561 #[doc = concat!("fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2562 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2564 #[doc = concat!(" ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())")]
2567 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2568 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2570 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2571 Self::from_be(Self::from_ne_bytes(bytes))
2574 /// Create an integer value from its representation as a byte array in
2577 #[doc = $to_xe_bytes_doc]
2582 #[doc = concat!("let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");")]
2583 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2586 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2589 /// use std::convert::TryInto;
2591 #[doc = concat!("fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2592 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2594 #[doc = concat!(" ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())")]
2597 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2598 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2600 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2601 Self::from_le(Self::from_ne_bytes(bytes))
2604 /// Create an integer value from its memory representation as a byte
2605 /// array in native endianness.
2607 /// As the target platform's native endianness is used, portable code
2608 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2609 /// appropriate instead.
2611 /// [`from_be_bytes`]: Self::from_be_bytes
2612 /// [`from_le_bytes`]: Self::from_le_bytes
2614 #[doc = $to_xe_bytes_doc]
2619 #[doc = concat!("let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {")]
2620 #[doc = concat!(" ", $be_bytes)]
2622 #[doc = concat!(" ", $le_bytes)]
2624 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2627 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2630 /// use std::convert::TryInto;
2632 #[doc = concat!("fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2633 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2635 #[doc = concat!(" ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())")]
2638 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2639 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2640 // SAFETY: const sound because integers are plain old datatypes so we can always
2641 // transmute to them
2643 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2644 // SAFETY: integers are plain old datatypes so we can always transmute to them
2645 unsafe { mem::transmute(bytes) }
2648 /// New code should prefer to use
2649 #[doc = concat!("[`", stringify!($SelfT), "::MIN", "`] instead.")]
2651 /// Returns the smallest value that can be represented by this integer type.
2652 #[stable(feature = "rust1", since = "1.0.0")]
2655 #[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
2656 #[rustc_deprecated(since = "TBD", reason = "replaced by the `MIN` associated constant on this type")]
2657 pub const fn min_value() -> Self {
2661 /// New code should prefer to use
2662 #[doc = concat!("[`", stringify!($SelfT), "::MAX", "`] instead.")]
2664 /// Returns the largest value that can be represented by this integer type.
2665 #[stable(feature = "rust1", since = "1.0.0")]
2668 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2669 #[rustc_deprecated(since = "TBD", reason = "replaced by the `MAX` associated constant on this type")]
2670 pub const fn max_value() -> Self {