1 macro_rules! int_impl {
2 ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $Min:expr, $Max:expr, $Feature:expr,
3 $EndFeature:expr, $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) => {
7 concat!("The smallest value that can be represented by this integer type.
14 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MIN, ", stringify!($Min), ");",
17 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
18 pub const MIN: Self = !0 ^ ((!0 as $UnsignedT) >> 1) as Self;
22 concat!("The largest value that can be represented by this integer type.
29 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($Max), ");",
32 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
33 pub const MAX: Self = !Self::MIN;
37 concat!("The size of this integer type in bits.
42 ", $Feature, "#![feature(int_bits_const)]
43 assert_eq!(", stringify!($SelfT), "::BITS, ", stringify!($BITS), ");",
46 #[unstable(feature = "int_bits_const", issue = "76904")]
47 pub const BITS: u32 = $BITS;
51 concat!("Converts a string slice in a given base to an integer.
53 The string is expected to be an optional `+` or `-` sign followed by digits.
54 Leading and trailing whitespace represent an error. Digits are a subset of these characters,
63 This function panics if `radix` is not in the range from 2 to 36.
70 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
73 #[stable(feature = "rust1", since = "1.0.0")]
74 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
75 from_str_radix(src, radix)
80 concat!("Returns the number of ones in the binary representation of `self`.
87 ", $Feature, "let n = 0b100_0000", stringify!($SelfT), ";
89 assert_eq!(n.count_ones(), 1);",
93 #[stable(feature = "rust1", since = "1.0.0")]
94 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
96 pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
100 concat!("Returns the number of zeros in the binary representation of `self`.
107 ", $Feature, "assert_eq!(", stringify!($SelfT), "::MAX.count_zeros(), 1);", $EndFeature, "
109 #[stable(feature = "rust1", since = "1.0.0")]
110 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
112 pub const fn count_zeros(self) -> u32 {
118 concat!("Returns the number of leading zeros in the binary representation of `self`.
125 ", $Feature, "let n = -1", stringify!($SelfT), ";
127 assert_eq!(n.leading_zeros(), 0);",
130 #[stable(feature = "rust1", since = "1.0.0")]
131 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
133 pub const fn leading_zeros(self) -> u32 {
134 (self as $UnsignedT).leading_zeros()
139 concat!("Returns the number of trailing zeros in the binary representation of `self`.
146 ", $Feature, "let n = -4", stringify!($SelfT), ";
148 assert_eq!(n.trailing_zeros(), 2);",
151 #[stable(feature = "rust1", since = "1.0.0")]
152 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
154 pub const fn trailing_zeros(self) -> u32 {
155 (self as $UnsignedT).trailing_zeros()
160 concat!("Returns the number of leading ones in the binary representation of `self`.
167 ", $Feature, "let n = -1", stringify!($SelfT), ";
169 assert_eq!(n.leading_ones(), ", stringify!($BITS), ");",
172 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
173 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
175 pub const fn leading_ones(self) -> u32 {
176 (self as $UnsignedT).leading_ones()
181 concat!("Returns the number of trailing ones in the binary representation of `self`.
188 ", $Feature, "let n = 3", stringify!($SelfT), ";
190 assert_eq!(n.trailing_ones(), 2);",
193 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
194 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
196 pub const fn trailing_ones(self) -> u32 {
197 (self as $UnsignedT).trailing_ones()
202 concat!("Shifts the bits to the left by a specified amount, `n`,
203 wrapping the truncated bits to the end of the resulting integer.
205 Please note this isn't the same operation as the `<<` shifting operator!
212 let n = ", $rot_op, stringify!($SelfT), ";
213 let m = ", $rot_result, ";
215 assert_eq!(n.rotate_left(", $rot, "), m);
217 #[stable(feature = "rust1", since = "1.0.0")]
218 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
219 #[must_use = "this returns the result of the operation, \
220 without modifying the original"]
222 pub const fn rotate_left(self, n: u32) -> Self {
223 (self as $UnsignedT).rotate_left(n) as Self
228 concat!("Shifts the bits to the right by a specified amount, `n`,
229 wrapping the truncated bits to the beginning of the resulting
232 Please note this isn't the same operation as the `>>` shifting operator!
239 let n = ", $rot_result, stringify!($SelfT), ";
240 let m = ", $rot_op, ";
242 assert_eq!(n.rotate_right(", $rot, "), m);
244 #[stable(feature = "rust1", since = "1.0.0")]
245 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
246 #[must_use = "this returns the result of the operation, \
247 without modifying the original"]
249 pub const fn rotate_right(self, n: u32) -> Self {
250 (self as $UnsignedT).rotate_right(n) as Self
255 concat!("Reverses the byte order of the integer.
262 let n = ", $swap_op, stringify!($SelfT), ";
264 let m = n.swap_bytes();
266 assert_eq!(m, ", $swapped, ");
268 #[stable(feature = "rust1", since = "1.0.0")]
269 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
271 pub const fn swap_bytes(self) -> Self {
272 (self as $UnsignedT).swap_bytes() as Self
277 concat!("Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
278 second least-significant bit becomes second most-significant bit, etc.
285 let n = ", $swap_op, stringify!($SelfT), ";
286 let m = n.reverse_bits();
288 assert_eq!(m, ", $reversed, ");
289 assert_eq!(0, 0", stringify!($SelfT), ".reverse_bits());
291 #[stable(feature = "reverse_bits", since = "1.37.0")]
292 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
295 pub const fn reverse_bits(self) -> Self {
296 (self as $UnsignedT).reverse_bits() as Self
301 concat!("Converts an integer from big endian to the target's endianness.
303 On big endian this is a no-op. On little endian the bytes are swapped.
310 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
312 if cfg!(target_endian = \"big\") {
313 assert_eq!(", stringify!($SelfT), "::from_be(n), n)
315 assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
319 #[stable(feature = "rust1", since = "1.0.0")]
320 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
322 pub const fn from_be(x: Self) -> Self {
323 #[cfg(target_endian = "big")]
327 #[cfg(not(target_endian = "big"))]
335 concat!("Converts an integer from little endian to the target's endianness.
337 On little endian this is a no-op. On big endian the bytes are swapped.
344 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
346 if cfg!(target_endian = \"little\") {
347 assert_eq!(", stringify!($SelfT), "::from_le(n), n)
349 assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
353 #[stable(feature = "rust1", since = "1.0.0")]
354 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
356 pub const fn from_le(x: Self) -> Self {
357 #[cfg(target_endian = "little")]
361 #[cfg(not(target_endian = "little"))]
369 concat!("Converts `self` to big endian from the target's endianness.
371 On big endian this is a no-op. On little endian the bytes are swapped.
378 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
380 if cfg!(target_endian = \"big\") {
381 assert_eq!(n.to_be(), n)
383 assert_eq!(n.to_be(), n.swap_bytes())
387 #[stable(feature = "rust1", since = "1.0.0")]
388 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
390 pub const fn to_be(self) -> Self { // or not to be?
391 #[cfg(target_endian = "big")]
395 #[cfg(not(target_endian = "big"))]
403 concat!("Converts `self` to little endian from the target's endianness.
405 On little endian this is a no-op. On big endian the bytes are swapped.
412 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
414 if cfg!(target_endian = \"little\") {
415 assert_eq!(n.to_le(), n)
417 assert_eq!(n.to_le(), n.swap_bytes())
421 #[stable(feature = "rust1", since = "1.0.0")]
422 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
424 pub const fn to_le(self) -> Self {
425 #[cfg(target_endian = "little")]
429 #[cfg(not(target_endian = "little"))]
437 concat!("Checked integer addition. Computes `self + rhs`, returning `None`
438 if overflow occurred.
445 ", $Feature, "assert_eq!((", stringify!($SelfT),
446 "::MAX - 2).checked_add(1), Some(", stringify!($SelfT), "::MAX - 1));
447 assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);",
450 #[stable(feature = "rust1", since = "1.0.0")]
451 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
452 #[must_use = "this returns the result of the operation, \
453 without modifying the original"]
455 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
456 let (a, b) = self.overflowing_add(rhs);
457 if unlikely!(b) {None} else {Some(a)}
462 concat!("Unchecked integer addition. Computes `self + rhs`, assuming overflow
463 cannot occur. This results in undefined behavior when `self + rhs > ", stringify!($SelfT),
464 "::MAX` or `self + rhs < ", stringify!($SelfT), "::MIN`."),
466 feature = "unchecked_math",
467 reason = "niche optimization path",
470 #[must_use = "this returns the result of the operation, \
471 without modifying the original"]
473 pub unsafe fn unchecked_add(self, rhs: Self) -> Self {
474 // SAFETY: the caller must uphold the safety contract for
476 unsafe { intrinsics::unchecked_add(self, rhs) }
481 concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
489 ", $Feature, "assert_eq!((", stringify!($SelfT),
490 "::MIN + 2).checked_sub(1), Some(", stringify!($SelfT), "::MIN + 1));
491 assert_eq!((", stringify!($SelfT), "::MIN + 2).checked_sub(3), None);",
494 #[stable(feature = "rust1", since = "1.0.0")]
495 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
496 #[must_use = "this returns the result of the operation, \
497 without modifying the original"]
499 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
500 let (a, b) = self.overflowing_sub(rhs);
501 if unlikely!(b) {None} else {Some(a)}
506 concat!("Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
507 cannot occur. This results in undefined behavior when `self - rhs > ", stringify!($SelfT),
508 "::MAX` or `self - rhs < ", stringify!($SelfT), "::MIN`."),
510 feature = "unchecked_math",
511 reason = "niche optimization path",
514 #[must_use = "this returns the result of the operation, \
515 without modifying the original"]
517 pub unsafe fn unchecked_sub(self, rhs: Self) -> Self {
518 // SAFETY: the caller must uphold the safety contract for
520 unsafe { intrinsics::unchecked_sub(self, rhs) }
525 concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
533 ", $Feature, "assert_eq!(", stringify!($SelfT),
534 "::MAX.checked_mul(1), Some(", stringify!($SelfT), "::MAX));
535 assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);",
538 #[stable(feature = "rust1", since = "1.0.0")]
539 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
540 #[must_use = "this returns the result of the operation, \
541 without modifying the original"]
543 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
544 let (a, b) = self.overflowing_mul(rhs);
545 if unlikely!(b) {None} else {Some(a)}
550 concat!("Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
551 cannot occur. This results in undefined behavior when `self * rhs > ", stringify!($SelfT),
552 "::MAX` or `self * rhs < ", stringify!($SelfT), "::MIN`."),
554 feature = "unchecked_math",
555 reason = "niche optimization path",
558 #[must_use = "this returns the result of the operation, \
559 without modifying the original"]
561 pub unsafe fn unchecked_mul(self, rhs: Self) -> Self {
562 // SAFETY: the caller must uphold the safety contract for
564 unsafe { intrinsics::unchecked_mul(self, rhs) }
569 concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
570 or the division results in overflow.
577 ", $Feature, "assert_eq!((", stringify!($SelfT),
578 "::MIN + 1).checked_div(-1), Some(", stringify!($Max), "));
579 assert_eq!(", stringify!($SelfT), "::MIN.checked_div(-1), None);
580 assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
583 #[stable(feature = "rust1", since = "1.0.0")]
584 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
585 #[must_use = "this returns the result of the operation, \
586 without modifying the original"]
588 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
589 if unlikely!(rhs == 0 || (self == Self::MIN && rhs == -1)) {
592 // SAFETY: div by zero and by INT_MIN have been checked above
593 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
599 concat!("Checked Euclidean division. Computes `self.div_euclid(rhs)`,
600 returning `None` if `rhs == 0` or the division results in overflow.
607 assert_eq!((", stringify!($SelfT),
608 "::MIN + 1).checked_div_euclid(-1), Some(", stringify!($Max), "));
609 assert_eq!(", stringify!($SelfT), "::MIN.checked_div_euclid(-1), None);
610 assert_eq!((1", stringify!($SelfT), ").checked_div_euclid(0), None);
612 #[stable(feature = "euclidean_division", since = "1.38.0")]
613 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
614 #[must_use = "this returns the result of the operation, \
615 without modifying the original"]
617 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
618 if unlikely!(rhs == 0 || (self == Self::MIN && rhs == -1)) {
621 Some(self.div_euclid(rhs))
627 concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
628 `rhs == 0` or the division results in overflow.
636 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
637 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
638 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
641 #[stable(feature = "wrapping", since = "1.7.0")]
642 #[rustc_const_unstable(feature = "const_checked_int_methods", issue = "53718")]
643 #[must_use = "this returns the result of the operation, \
644 without modifying the original"]
646 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
647 if unlikely!(rhs == 0 || (self == Self::MIN && rhs == -1)) {
650 // SAFETY: div by zero and by INT_MIN have been checked above
651 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
657 concat!("Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`
658 if `rhs == 0` or the division results in overflow.
665 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));
666 assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);
667 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem_euclid(-1), None);
669 #[stable(feature = "euclidean_division", since = "1.38.0")]
670 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
671 #[must_use = "this returns the result of the operation, \
672 without modifying the original"]
674 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
675 if unlikely!(rhs == 0 || (self == Self::MIN && rhs == -1)) {
678 Some(self.rem_euclid(rhs))
684 concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
692 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
693 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
696 #[stable(feature = "wrapping", since = "1.7.0")]
697 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
699 pub const fn checked_neg(self) -> Option<Self> {
700 let (a, b) = self.overflowing_neg();
701 if unlikely!(b) {None} else {Some(a)}
706 concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
707 than or equal to the number of bits in `self`.
714 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
715 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
718 #[stable(feature = "wrapping", since = "1.7.0")]
719 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
720 #[must_use = "this returns the result of the operation, \
721 without modifying the original"]
723 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
724 let (a, b) = self.overflowing_shl(rhs);
725 if unlikely!(b) {None} else {Some(a)}
730 concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
731 larger than or equal to the number of bits in `self`.
738 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
739 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
742 #[stable(feature = "wrapping", since = "1.7.0")]
743 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
744 #[must_use = "this returns the result of the operation, \
745 without modifying the original"]
747 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
748 let (a, b) = self.overflowing_shr(rhs);
749 if unlikely!(b) {None} else {Some(a)}
754 concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
763 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
764 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
767 #[stable(feature = "no_panic_abs", since = "1.13.0")]
768 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
770 pub const fn checked_abs(self) -> Option<Self> {
771 if self.is_negative() {
780 concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
788 ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
789 assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);",
793 #[stable(feature = "no_panic_pow", since = "1.34.0")]
794 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
795 #[must_use = "this returns the result of the operation, \
796 without modifying the original"]
798 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
803 let mut acc: Self = 1;
807 acc = try_opt!(acc.checked_mul(base));
810 base = try_opt!(base.checked_mul(base));
812 // since exp!=0, finally the exp must be 1.
813 // Deal with the final bit of the exponent separately, since
814 // squaring the base afterwards is not necessary and may cause a
815 // needless overflow.
816 Some(try_opt!(acc.checked_mul(base)))
821 concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
822 bounds instead of overflowing.
829 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
830 assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(100), ", stringify!($SelfT),
832 assert_eq!(", stringify!($SelfT), "::MIN.saturating_add(-1), ", stringify!($SelfT),
837 #[stable(feature = "rust1", since = "1.0.0")]
838 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
839 #[must_use = "this returns the result of the operation, \
840 without modifying the original"]
842 pub const fn saturating_add(self, rhs: Self) -> Self {
843 intrinsics::saturating_add(self, rhs)
848 concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
849 numeric bounds instead of overflowing.
856 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
857 assert_eq!(", stringify!($SelfT), "::MIN.saturating_sub(100), ", stringify!($SelfT),
859 assert_eq!(", stringify!($SelfT), "::MAX.saturating_sub(-1), ", stringify!($SelfT),
863 #[stable(feature = "rust1", since = "1.0.0")]
864 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
865 #[must_use = "this returns the result of the operation, \
866 without modifying the original"]
868 pub const fn saturating_sub(self, rhs: Self) -> Self {
869 intrinsics::saturating_sub(self, rhs)
874 concat!("Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
875 instead of overflowing.
882 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_neg(), -100);
883 assert_eq!((-100", stringify!($SelfT), ").saturating_neg(), 100);
884 assert_eq!(", stringify!($SelfT), "::MIN.saturating_neg(), ", stringify!($SelfT),
886 assert_eq!(", stringify!($SelfT), "::MAX.saturating_neg(), ", stringify!($SelfT),
891 #[stable(feature = "saturating_neg", since = "1.45.0")]
892 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
894 pub const fn saturating_neg(self) -> Self {
895 intrinsics::saturating_sub(0, self)
900 concat!("Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
901 MIN` instead of overflowing.
908 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_abs(), 100);
909 assert_eq!((-100", stringify!($SelfT), ").saturating_abs(), 100);
910 assert_eq!(", stringify!($SelfT), "::MIN.saturating_abs(), ", stringify!($SelfT),
912 assert_eq!((", stringify!($SelfT), "::MIN + 1).saturating_abs(), ", stringify!($SelfT),
917 #[stable(feature = "saturating_neg", since = "1.45.0")]
918 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
920 pub const fn saturating_abs(self) -> Self {
921 if self.is_negative() {
922 self.saturating_neg()
930 concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
931 numeric bounds instead of overflowing.
939 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
940 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
941 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
944 #[stable(feature = "wrapping", since = "1.7.0")]
945 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
946 #[must_use = "this returns the result of the operation, \
947 without modifying the original"]
949 pub const fn saturating_mul(self, rhs: Self) -> Self {
950 match self.checked_mul(rhs) {
952 None => if (self < 0) == (rhs < 0) {
962 concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
963 saturating at the numeric bounds instead of overflowing.
971 assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
972 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
973 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
976 #[stable(feature = "no_panic_pow", since = "1.34.0")]
977 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
978 #[must_use = "this returns the result of the operation, \
979 without modifying the original"]
981 pub const fn saturating_pow(self, exp: u32) -> Self {
982 match self.checked_pow(exp) {
984 None if self < 0 && exp % 2 == 1 => Self::MIN,
991 concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
992 boundary of the type.
999 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
1000 assert_eq!(", stringify!($SelfT), "::MAX.wrapping_add(2), ", stringify!($SelfT),
1004 #[stable(feature = "rust1", since = "1.0.0")]
1005 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1006 #[must_use = "this returns the result of the operation, \
1007 without modifying the original"]
1009 pub const fn wrapping_add(self, rhs: Self) -> Self {
1010 intrinsics::wrapping_add(self, rhs)
1015 concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1016 boundary of the type.
1023 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
1024 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::MAX), ",
1025 stringify!($SelfT), "::MAX);",
1028 #[stable(feature = "rust1", since = "1.0.0")]
1029 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1030 #[must_use = "this returns the result of the operation, \
1031 without modifying the original"]
1033 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1034 intrinsics::wrapping_sub(self, rhs)
1039 concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1040 the boundary of the type.
1047 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
1048 assert_eq!(11i8.wrapping_mul(12), -124);",
1051 #[stable(feature = "rust1", since = "1.0.0")]
1052 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1053 #[must_use = "this returns the result of the operation, \
1054 without modifying the original"]
1056 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1057 intrinsics::wrapping_mul(self, rhs)
1062 concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1063 boundary of the type.
1065 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1066 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1067 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1071 This function will panic if `rhs` is 0.
1078 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
1079 assert_eq!((-128i8).wrapping_div(-1), -128);",
1082 #[stable(feature = "num_wrapping", since = "1.2.0")]
1083 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
1084 #[must_use = "this returns the result of the operation, \
1085 without modifying the original"]
1087 pub const fn wrapping_div(self, rhs: Self) -> Self {
1088 self.overflowing_div(rhs).0
1093 concat!("Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
1094 wrapping around at the boundary of the type.
1096 Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1097 for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1098 type. In this case, this method returns `MIN` itself.
1102 This function will panic if `rhs` is 0.
1109 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);
1110 assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
1112 #[stable(feature = "euclidean_division", since = "1.38.0")]
1113 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1114 #[must_use = "this returns the result of the operation, \
1115 without modifying the original"]
1117 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
1118 self.overflowing_div_euclid(rhs).0
1123 concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1124 boundary of the type.
1126 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1127 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1128 this function returns `0`.
1132 This function will panic if `rhs` is 0.
1139 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
1140 assert_eq!((-128i8).wrapping_rem(-1), 0);",
1143 #[stable(feature = "num_wrapping", since = "1.2.0")]
1144 #[rustc_const_unstable(feature = "const_wrapping_int_methods", issue = "53718")]
1145 #[must_use = "this returns the result of the operation, \
1146 without modifying the original"]
1148 pub const fn wrapping_rem(self, rhs: Self) -> Self {
1149 self.overflowing_rem(rhs).0
1154 concat!("Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
1155 at the boundary of the type.
1157 Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1158 for the type). In this case, this method returns 0.
1162 This function will panic if `rhs` is 0.
1169 assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);
1170 assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
1172 #[stable(feature = "euclidean_division", since = "1.38.0")]
1173 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1174 #[must_use = "this returns the result of the operation, \
1175 without modifying the original"]
1177 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1178 self.overflowing_rem_euclid(rhs).0
1183 concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1186 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1187 is the negative minimal value for the type); this is a positive value that is too large to represent
1188 in the type. In such a case, this function returns `MIN` itself.
1195 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
1196 assert_eq!(", stringify!($SelfT), "::MIN.wrapping_neg(), ", stringify!($SelfT),
1200 #[stable(feature = "num_wrapping", since = "1.2.0")]
1201 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1203 pub const fn wrapping_neg(self) -> Self {
1204 self.overflowing_neg().0
1209 concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1210 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1212 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1213 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1214 The primitive integer types all implement a `[`rotate_left`](#method.rotate_left) function,
1215 which may be what you want instead.
1222 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
1223 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
1226 #[stable(feature = "num_wrapping", since = "1.2.0")]
1227 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1228 #[must_use = "this returns the result of the operation, \
1229 without modifying the original"]
1231 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1232 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1235 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1241 concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1242 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1244 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1245 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1246 end. The primitive integer types all implement a [`rotate_right`](#method.rotate_right) function,
1247 which may be what you want instead.
1254 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
1255 assert_eq!((-128i16).wrapping_shr(64), -128);",
1258 #[stable(feature = "num_wrapping", since = "1.2.0")]
1259 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1260 #[must_use = "this returns the result of the operation, \
1261 without modifying the original"]
1263 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1264 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1267 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1273 concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1274 the boundary of the type.
1276 The only case where such wrapping can occur is when one takes the absolute value of the negative
1277 minimal value for the type; this is a positive value that is too large to represent in the type. In
1278 such a case, this function returns `MIN` itself.
1285 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
1286 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
1287 assert_eq!(", stringify!($SelfT), "::MIN.wrapping_abs(), ", stringify!($SelfT),
1289 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1292 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1293 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1294 #[allow(unused_attributes)]
1296 pub const fn wrapping_abs(self) -> Self {
1297 if self.is_negative() {
1306 concat!("Computes the absolute value of `self` without any wrapping
1315 ", $Feature, "#![feature(unsigned_abs)]
1316 assert_eq!(100", stringify!($SelfT), ".unsigned_abs(), 100", stringify!($UnsignedT), ");
1317 assert_eq!((-100", stringify!($SelfT), ").unsigned_abs(), 100", stringify!($UnsignedT), ");
1318 assert_eq!((-128i8).unsigned_abs(), 128u8);",
1321 #[unstable(feature = "unsigned_abs", issue = "74913")]
1323 pub const fn unsigned_abs(self) -> $UnsignedT {
1324 self.wrapping_abs() as $UnsignedT
1329 concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1330 wrapping around at the boundary of the type.
1337 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);
1338 assert_eq!(3i8.wrapping_pow(5), -13);
1339 assert_eq!(3i8.wrapping_pow(6), -39);",
1342 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1343 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1344 #[must_use = "this returns the result of the operation, \
1345 without modifying the original"]
1347 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
1351 let mut base = self;
1352 let mut acc: Self = 1;
1356 acc = acc.wrapping_mul(base);
1359 base = base.wrapping_mul(base);
1362 // since exp!=0, finally the exp must be 1.
1363 // Deal with the final bit of the exponent separately, since
1364 // squaring the base afterwards is not necessary and may cause a
1365 // needless overflow.
1366 acc.wrapping_mul(base)
1371 concat!("Calculates `self` + `rhs`
1373 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1374 occur. If an overflow would have occurred then the wrapped value is returned.
1382 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1383 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
1384 "::MIN, true));", $EndFeature, "
1386 #[stable(feature = "wrapping", since = "1.7.0")]
1387 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1388 #[must_use = "this returns the result of the operation, \
1389 without modifying the original"]
1391 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1392 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1398 concat!("Calculates `self` - `rhs`
1400 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1401 would occur. If an overflow would have occurred then the wrapped value is returned.
1409 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
1410 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
1411 "::MAX, true));", $EndFeature, "
1413 #[stable(feature = "wrapping", since = "1.7.0")]
1414 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1415 #[must_use = "this returns the result of the operation, \
1416 without modifying the original"]
1418 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1419 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1425 concat!("Calculates the multiplication of `self` and `rhs`.
1427 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1428 would occur. If an overflow would have occurred then the wrapped value is returned.
1435 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1436 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1439 #[stable(feature = "wrapping", since = "1.7.0")]
1440 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1441 #[must_use = "this returns the result of the operation, \
1442 without modifying the original"]
1444 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1445 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1451 concat!("Calculates the divisor when `self` is divided by `rhs`.
1453 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1454 occur. If an overflow would occur then self is returned.
1458 This function will panic if `rhs` is 0.
1466 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1467 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1472 #[stable(feature = "wrapping", since = "1.7.0")]
1473 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
1474 #[must_use = "this returns the result of the operation, \
1475 without modifying the original"]
1476 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1477 if unlikely!(self == Self::MIN && rhs == -1) {
1486 concat!("Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1488 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1489 occur. If an overflow would occur then `self` is returned.
1493 This function will panic if `rhs` is 0.
1500 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));
1501 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euclid(-1), (", stringify!($SelfT),
1505 #[stable(feature = "euclidean_division", since = "1.38.0")]
1506 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1507 #[must_use = "this returns the result of the operation, \
1508 without modifying the original"]
1509 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1510 if unlikely!(self == Self::MIN && rhs == -1) {
1513 (self.div_euclid(rhs), false)
1519 concat!("Calculates the remainder when `self` is divided by `rhs`.
1521 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1522 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1526 This function will panic if `rhs` is 0.
1534 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1535 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1539 #[stable(feature = "wrapping", since = "1.7.0")]
1540 #[rustc_const_unstable(feature = "const_overflowing_int_methods", issue = "53718")]
1541 #[must_use = "this returns the result of the operation, \
1542 without modifying the original"]
1543 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1544 if unlikely!(self == Self::MIN && rhs == -1) {
1554 concat!("Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
1556 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1557 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1561 This function will panic if `rhs` is 0.
1568 assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));
1569 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem_euclid(-1), (0, true));
1571 #[stable(feature = "euclidean_division", since = "1.38.0")]
1572 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1573 #[must_use = "this returns the result of the operation, \
1574 without modifying the original"]
1576 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1577 if unlikely!(self == Self::MIN && rhs == -1) {
1580 (self.rem_euclid(rhs), false)
1587 concat!("Negates self, overflowing if this is equal to the minimum value.
1589 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1590 happened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the
1591 minimum value will be returned again and `true` will be returned for an overflow happening.
1598 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1599 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1600 "::MIN, true));", $EndFeature, "
1603 #[stable(feature = "wrapping", since = "1.7.0")]
1604 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1605 #[allow(unused_attributes)]
1606 pub const fn overflowing_neg(self) -> (Self, bool) {
1607 if unlikely!(self == Self::MIN) {
1616 concat!("Shifts self left by `rhs` bits.
1618 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1619 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1620 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1627 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1628 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1631 #[stable(feature = "wrapping", since = "1.7.0")]
1632 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1633 #[must_use = "this returns the result of the operation, \
1634 without modifying the original"]
1636 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1637 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1642 concat!("Shifts self right by `rhs` bits.
1644 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1645 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1646 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1653 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1654 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1657 #[stable(feature = "wrapping", since = "1.7.0")]
1658 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1659 #[must_use = "this returns the result of the operation, \
1660 without modifying the original"]
1662 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1663 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1668 concat!("Computes the absolute value of `self`.
1670 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1671 happened. If self is the minimum value (e.g., ", stringify!($SelfT), "::MIN for values of type
1672 ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1673 for an overflow happening.
1680 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1681 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1682 assert_eq!((", stringify!($SelfT), "::MIN).overflowing_abs(), (", stringify!($SelfT),
1686 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1687 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1689 pub const fn overflowing_abs(self) -> (Self, bool) {
1690 (self.wrapping_abs(), self == Self::MIN)
1695 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1697 Returns a tuple of the exponentiation along with a bool indicating
1698 whether an overflow happened.
1705 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));
1706 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
1709 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1710 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1711 #[must_use = "this returns the result of the operation, \
1712 without modifying the original"]
1714 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1718 let mut base = self;
1719 let mut acc: Self = 1;
1720 let mut overflown = false;
1721 // Scratch space for storing results of overflowing_mul.
1726 r = acc.overflowing_mul(base);
1731 r = base.overflowing_mul(base);
1736 // since exp!=0, finally the exp must be 1.
1737 // Deal with the final bit of the exponent separately, since
1738 // squaring the base afterwards is not necessary and may cause a
1739 // needless overflow.
1740 r = acc.overflowing_mul(base);
1747 concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1754 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
1756 assert_eq!(x.pow(5), 32);",
1759 #[stable(feature = "rust1", since = "1.0.0")]
1760 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1761 #[must_use = "this returns the result of the operation, \
1762 without modifying the original"]
1764 #[rustc_inherit_overflow_checks]
1765 pub const fn pow(self, mut exp: u32) -> Self {
1769 let mut base = self;
1780 // since exp!=0, finally the exp must be 1.
1781 // Deal with the final bit of the exponent separately, since
1782 // squaring the base afterwards is not necessary and may cause a
1783 // needless overflow.
1789 concat!("Calculates the quotient of Euclidean division of `self` by `rhs`.
1791 This computes the integer `n` such that `self = n * rhs + self.rem_euclid(rhs)`,
1792 with `0 <= self.rem_euclid(rhs) < rhs`.
1794 In other words, the result is `self / rhs` rounded to the integer `n`
1795 such that `self >= n * rhs`.
1796 If `self > 0`, this is equal to round towards zero (the default in Rust);
1797 if `self < 0`, this is equal to round towards +/- infinity.
1801 This function will panic if `rhs` is 0 or the division results in overflow.
1808 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1811 assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
1812 assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
1813 assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
1814 assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
1816 #[stable(feature = "euclidean_division", since = "1.38.0")]
1817 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1818 #[must_use = "this returns the result of the operation, \
1819 without modifying the original"]
1821 #[rustc_inherit_overflow_checks]
1822 pub const fn div_euclid(self, rhs: Self) -> Self {
1825 return if rhs > 0 { q - 1 } else { q + 1 }
1833 concat!("Calculates the least nonnegative remainder of `self (mod rhs)`.
1835 This is done as if by the Euclidean division algorithm -- given
1836 `r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) + r`, and
1837 `0 <= r < abs(rhs)`.
1841 This function will panic if `rhs` is 0 or the division results in overflow.
1848 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1851 assert_eq!(a.rem_euclid(b), 3);
1852 assert_eq!((-a).rem_euclid(b), 1);
1853 assert_eq!(a.rem_euclid(-b), 3);
1854 assert_eq!((-a).rem_euclid(-b), 1);
1856 #[stable(feature = "euclidean_division", since = "1.38.0")]
1857 #[rustc_const_unstable(feature = "const_euclidean_int_methods", issue = "53718")]
1858 #[must_use = "this returns the result of the operation, \
1859 without modifying the original"]
1861 #[rustc_inherit_overflow_checks]
1862 pub const fn rem_euclid(self, rhs: Self) -> Self {
1877 concat!("Computes the absolute value of `self`.
1881 The absolute value of `", stringify!($SelfT), "::MIN` cannot be represented as an
1882 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
1883 code in debug mode will trigger a panic on this case and optimized code will return `",
1884 stringify!($SelfT), "::MIN` without a panic.
1891 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
1892 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
1895 #[stable(feature = "rust1", since = "1.0.0")]
1896 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1897 #[allow(unused_attributes)]
1899 #[rustc_inherit_overflow_checks]
1900 pub const fn abs(self) -> Self {
1901 // Note that the #[inline] above means that the overflow
1902 // semantics of the subtraction depend on the crate we're being
1904 if self.is_negative() {
1913 concat!("Returns a number representing sign of `self`.
1915 - `0` if the number is zero
1916 - `1` if the number is positive
1917 - `-1` if the number is negative
1924 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
1925 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
1926 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
1929 #[stable(feature = "rust1", since = "1.0.0")]
1930 #[rustc_const_stable(feature = "const_int_sign", since = "1.47.0")]
1932 pub const fn signum(self) -> Self {
1942 concat!("Returns `true` if `self` is positive and `false` if the number is zero or
1950 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
1951 assert!(!(-10", stringify!($SelfT), ").is_positive());",
1954 #[stable(feature = "rust1", since = "1.0.0")]
1955 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1957 pub const fn is_positive(self) -> bool { self > 0 }
1961 concat!("Returns `true` if `self` is negative and `false` if the number is zero or
1969 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
1970 assert!(!10", stringify!($SelfT), ".is_negative());",
1973 #[stable(feature = "rust1", since = "1.0.0")]
1974 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1976 pub const fn is_negative(self) -> bool { self < 0 }
1980 concat!("Return the memory representation of this integer as a byte array in
1981 big-endian (network) byte order.
1988 let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();
1989 assert_eq!(bytes, ", $be_bytes, ");
1991 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
1992 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
1994 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
1995 self.to_be().to_ne_bytes()
2000 concat!("Return the memory representation of this integer as a byte array in
2001 little-endian byte order.
2008 let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();
2009 assert_eq!(bytes, ", $le_bytes, ");
2011 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2012 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2014 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2015 self.to_le().to_ne_bytes()
2021 Return the memory representation of this integer as a byte array in
2024 As the target platform's native endianness is used, portable code
2025 should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2030 [`to_be_bytes`]: #method.to_be_bytes
2031 [`to_le_bytes`]: #method.to_le_bytes
2036 let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();
2039 if cfg!(target_endian = \"big\") {
2046 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2047 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2048 // SAFETY: const sound because integers are plain old datatypes so we can always
2049 // transmute them to arrays of bytes
2050 #[rustc_allow_const_fn_unstable(const_fn_transmute)]
2052 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2053 // SAFETY: integers are plain old datatypes so we can always transmute them to
2055 unsafe { mem::transmute(self) }
2061 Return the memory representation of this integer as a byte array in
2064 [`to_ne_bytes`] should be preferred over this whenever possible.
2066 [`to_ne_bytes`]: #method.to_ne_bytes
2073 #![feature(num_as_ne_bytes)]
2074 let num = ", $swap_op, stringify!($SelfT), ";
2075 let bytes = num.as_ne_bytes();
2078 if cfg!(target_endian = \"big\") {
2085 #[unstable(feature = "num_as_ne_bytes", issue = "76976")]
2087 pub fn as_ne_bytes(&self) -> &[u8; mem::size_of::<Self>()] {
2088 // SAFETY: integers are plain old datatypes so we can always transmute them to
2090 unsafe { &*(self as *const Self as *const _) }
2095 concat!("Create an integer value from its representation as a byte array in
2103 let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");
2104 assert_eq!(value, ", $swap_op, ");
2107 When starting from a slice rather than an array, fallible conversion APIs can be used:
2110 use std::convert::TryInto;
2112 fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2113 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2115 ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())
2118 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2119 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2121 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2122 Self::from_be(Self::from_ne_bytes(bytes))
2128 Create an integer value from its representation as a byte array in
2136 let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");
2137 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 fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2146 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2148 ", stringify!($SelfT), "::from_le_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_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2155 Self::from_le(Self::from_ne_bytes(bytes))
2160 concat!("Create an integer value from its memory representation as a byte
2161 array in native endianness.
2163 As the target platform's native endianness is used, portable code
2164 likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2165 appropriate instead.
2167 [`from_be_bytes`]: #method.from_be_bytes
2168 [`from_le_bytes`]: #method.from_le_bytes
2175 let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {
2180 assert_eq!(value, ", $swap_op, ");
2183 When starting from a slice rather than an array, fallible conversion APIs can be used:
2186 use std::convert::TryInto;
2188 fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {
2189 let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());
2191 ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())
2194 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2195 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2196 // SAFETY: const sound because integers are plain old datatypes so we can always
2197 // transmute to them
2198 #[rustc_allow_const_fn_unstable(const_fn_transmute)]
2200 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2201 // SAFETY: integers are plain old datatypes so we can always transmute to them
2202 unsafe { mem::transmute(bytes) }
2207 concat!("**This method is soft-deprecated.**
2209 Although using it won’t cause a compilation warning,
2210 new code should use [`", stringify!($SelfT), "::MIN", "`](#associatedconstant.MIN) instead.
2212 Returns the smallest value that can be represented by this integer type."),
2213 #[stable(feature = "rust1", since = "1.0.0")]
2216 #[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
2217 pub const fn min_value() -> Self {
2223 concat!("**This method is soft-deprecated.**
2225 Although using it won’t cause a compilation warning,
2226 new code should use [`", stringify!($SelfT), "::MAX", "`](#associatedconstant.MAX) instead.
2228 Returns the largest value that can be represented by this integer type."),
2229 #[stable(feature = "rust1", since = "1.0.0")]
2232 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2233 pub const fn max_value() -> Self {