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")]
84 #[must_use = "this returns the result of the operation, \
85 without modifying the original"]
87 pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
89 /// Returns the number of zeros in the binary representation of `self`.
96 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.count_zeros(), 1);")]
98 #[stable(feature = "rust1", since = "1.0.0")]
99 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
100 #[must_use = "this returns the result of the operation, \
101 without modifying the original"]
103 pub const fn count_zeros(self) -> u32 {
107 /// Returns the number of leading zeros in the binary representation of `self`.
114 #[doc = concat!("let n = -1", stringify!($SelfT), ";")]
116 /// assert_eq!(n.leading_zeros(), 0);
118 #[stable(feature = "rust1", since = "1.0.0")]
119 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
120 #[must_use = "this returns the result of the operation, \
121 without modifying the original"]
123 pub const fn leading_zeros(self) -> u32 {
124 (self as $UnsignedT).leading_zeros()
127 /// Returns the number of trailing zeros in the binary representation of `self`.
134 #[doc = concat!("let n = -4", stringify!($SelfT), ";")]
136 /// assert_eq!(n.trailing_zeros(), 2);
138 #[stable(feature = "rust1", since = "1.0.0")]
139 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
140 #[must_use = "this returns the result of the operation, \
141 without modifying the original"]
143 pub const fn trailing_zeros(self) -> u32 {
144 (self as $UnsignedT).trailing_zeros()
147 /// Returns the number of leading ones in the binary representation of `self`.
154 #[doc = concat!("let n = -1", stringify!($SelfT), ";")]
156 #[doc = concat!("assert_eq!(n.leading_ones(), ", stringify!($BITS), ");")]
158 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
159 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
160 #[must_use = "this returns the result of the operation, \
161 without modifying the original"]
163 pub const fn leading_ones(self) -> u32 {
164 (self as $UnsignedT).leading_ones()
167 /// Returns the number of trailing ones in the binary representation of `self`.
174 #[doc = concat!("let n = 3", stringify!($SelfT), ";")]
176 /// assert_eq!(n.trailing_ones(), 2);
178 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
179 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
180 #[must_use = "this returns the result of the operation, \
181 without modifying the original"]
183 pub const fn trailing_ones(self) -> u32 {
184 (self as $UnsignedT).trailing_ones()
187 /// Shifts the bits to the left by a specified amount, `n`,
188 /// wrapping the truncated bits to the end of the resulting integer.
190 /// Please note this isn't the same operation as the `<<` shifting operator!
197 #[doc = concat!("let n = ", $rot_op, stringify!($SelfT), ";")]
198 #[doc = concat!("let m = ", $rot_result, ";")]
200 #[doc = concat!("assert_eq!(n.rotate_left(", $rot, "), m);")]
202 #[stable(feature = "rust1", since = "1.0.0")]
203 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
204 #[must_use = "this returns the result of the operation, \
205 without modifying the original"]
207 pub const fn rotate_left(self, n: u32) -> Self {
208 (self as $UnsignedT).rotate_left(n) as Self
211 /// Shifts the bits to the right by a specified amount, `n`,
212 /// wrapping the truncated bits to the beginning of the resulting
215 /// Please note this isn't the same operation as the `>>` shifting operator!
222 #[doc = concat!("let n = ", $rot_result, stringify!($SelfT), ";")]
223 #[doc = concat!("let m = ", $rot_op, ";")]
225 #[doc = concat!("assert_eq!(n.rotate_right(", $rot, "), m);")]
227 #[stable(feature = "rust1", since = "1.0.0")]
228 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
229 #[must_use = "this returns the result of the operation, \
230 without modifying the original"]
232 pub const fn rotate_right(self, n: u32) -> Self {
233 (self as $UnsignedT).rotate_right(n) as Self
236 /// Reverses the byte order of the integer.
243 #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
245 /// let m = n.swap_bytes();
247 #[doc = concat!("assert_eq!(m, ", $swapped, ");")]
249 #[stable(feature = "rust1", since = "1.0.0")]
250 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
251 #[must_use = "this returns the result of the operation, \
252 without modifying the original"]
254 pub const fn swap_bytes(self) -> Self {
255 (self as $UnsignedT).swap_bytes() as Self
258 /// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
259 /// second least-significant bit becomes second most-significant bit, etc.
266 #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
267 /// let m = n.reverse_bits();
269 #[doc = concat!("assert_eq!(m, ", $reversed, ");")]
270 #[doc = concat!("assert_eq!(0, 0", stringify!($SelfT), ".reverse_bits());")]
272 #[stable(feature = "reverse_bits", since = "1.37.0")]
273 #[rustc_const_stable(feature = "const_int_methods", since = "1.37.0")]
274 #[must_use = "this returns the result of the operation, \
275 without modifying the original"]
277 pub const fn reverse_bits(self) -> Self {
278 (self as $UnsignedT).reverse_bits() as Self
281 /// Converts an integer from big endian to the target's endianness.
283 /// On big endian this is a no-op. On little endian the bytes are swapped.
290 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
292 /// if cfg!(target_endian = "big") {
293 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_be(n), n)")]
295 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())")]
298 #[stable(feature = "rust1", since = "1.0.0")]
299 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
302 pub const fn from_be(x: Self) -> Self {
303 #[cfg(target_endian = "big")]
307 #[cfg(not(target_endian = "big"))]
313 /// Converts an integer from little endian to the target's endianness.
315 /// On little endian this is a no-op. On big endian the bytes are swapped.
322 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
324 /// if cfg!(target_endian = "little") {
325 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_le(n), n)")]
327 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())")]
330 #[stable(feature = "rust1", since = "1.0.0")]
331 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
334 pub const fn from_le(x: Self) -> Self {
335 #[cfg(target_endian = "little")]
339 #[cfg(not(target_endian = "little"))]
345 /// Converts `self` to big endian from the target's endianness.
347 /// On big endian this is a no-op. On little endian the bytes are swapped.
354 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
356 /// if cfg!(target_endian = "big") {
357 /// assert_eq!(n.to_be(), n)
359 /// assert_eq!(n.to_be(), n.swap_bytes())
362 #[stable(feature = "rust1", since = "1.0.0")]
363 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
364 #[must_use = "this returns the result of the operation, \
365 without modifying the original"]
367 pub const fn to_be(self) -> Self { // or not to be?
368 #[cfg(target_endian = "big")]
372 #[cfg(not(target_endian = "big"))]
378 /// Converts `self` to little endian from the target's endianness.
380 /// On little endian this is a no-op. On big endian the bytes are swapped.
387 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
389 /// if cfg!(target_endian = "little") {
390 /// assert_eq!(n.to_le(), n)
392 /// assert_eq!(n.to_le(), n.swap_bytes())
395 #[stable(feature = "rust1", since = "1.0.0")]
396 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
397 #[must_use = "this returns the result of the operation, \
398 without modifying the original"]
400 pub const fn to_le(self) -> Self {
401 #[cfg(target_endian = "little")]
405 #[cfg(not(target_endian = "little"))]
411 /// Checked integer addition. Computes `self + rhs`, returning `None`
412 /// if overflow occurred.
419 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(1), Some(", stringify!($SelfT), "::MAX - 1));")]
420 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);")]
422 #[stable(feature = "rust1", since = "1.0.0")]
423 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
424 #[must_use = "this returns the result of the operation, \
425 without modifying the original"]
427 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
428 let (a, b) = self.overflowing_add(rhs);
429 if unlikely!(b) {None} else {Some(a)}
432 /// Unchecked integer addition. Computes `self + rhs`, assuming overflow
437 /// This results in undefined behavior when
438 #[doc = concat!("`self + rhs > ", stringify!($SelfT), "::MAX` or `self + rhs < ", stringify!($SelfT), "::MIN`,")]
439 /// i.e. when [`checked_add`] would return `None`.
441 #[doc = concat!("[`checked_add`]: ", stringify!($SelfT), "::checked_add")]
443 feature = "unchecked_math",
444 reason = "niche optimization path",
447 #[must_use = "this returns the result of the operation, \
448 without modifying the original"]
449 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
451 pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
452 // SAFETY: the caller must uphold the safety contract for
454 unsafe { intrinsics::unchecked_add(self, rhs) }
457 /// Checked addition with an unsigned integer. Computes `self + rhs`,
458 /// returning `None` if overflow occurred.
465 /// # #![feature(mixed_integer_ops)]
466 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_add_unsigned(2), Some(3));")]
467 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add_unsigned(3), None);")]
469 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
470 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
471 #[must_use = "this returns the result of the operation, \
472 without modifying the original"]
474 pub const fn checked_add_unsigned(self, rhs: $UnsignedT) -> Option<Self> {
475 let (a, b) = self.overflowing_add_unsigned(rhs);
476 if unlikely!(b) {None} else {Some(a)}
479 /// Checked integer subtraction. Computes `self - rhs`, returning `None` if
480 /// overflow occurred.
487 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 2).checked_sub(1), Some(", stringify!($SelfT), "::MIN + 1));")]
488 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 2).checked_sub(3), None);")]
490 #[stable(feature = "rust1", since = "1.0.0")]
491 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
492 #[must_use = "this returns the result of the operation, \
493 without modifying the original"]
495 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
496 let (a, b) = self.overflowing_sub(rhs);
497 if unlikely!(b) {None} else {Some(a)}
500 /// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
505 /// This results in undefined behavior when
506 #[doc = concat!("`self - rhs > ", stringify!($SelfT), "::MAX` or `self - rhs < ", stringify!($SelfT), "::MIN`,")]
507 /// i.e. when [`checked_sub`] would return `None`.
509 #[doc = concat!("[`checked_sub`]: ", stringify!($SelfT), "::checked_sub")]
511 feature = "unchecked_math",
512 reason = "niche optimization path",
515 #[must_use = "this returns the result of the operation, \
516 without modifying the original"]
517 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
519 pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
520 // SAFETY: the caller must uphold the safety contract for
522 unsafe { intrinsics::unchecked_sub(self, rhs) }
525 /// Checked subtraction with an unsigned integer. Computes `self - rhs`,
526 /// returning `None` if overflow occurred.
533 /// # #![feature(mixed_integer_ops)]
534 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_sub_unsigned(2), Some(-1));")]
535 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 2).checked_sub_unsigned(3), None);")]
537 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
538 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
539 #[must_use = "this returns the result of the operation, \
540 without modifying the original"]
542 pub const fn checked_sub_unsigned(self, rhs: $UnsignedT) -> Option<Self> {
543 let (a, b) = self.overflowing_sub_unsigned(rhs);
544 if unlikely!(b) {None} else {Some(a)}
547 /// Checked integer multiplication. Computes `self * rhs`, returning `None` if
548 /// overflow occurred.
555 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(1), Some(", stringify!($SelfT), "::MAX));")]
556 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);")]
558 #[stable(feature = "rust1", since = "1.0.0")]
559 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
560 #[must_use = "this returns the result of the operation, \
561 without modifying the original"]
563 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
564 let (a, b) = self.overflowing_mul(rhs);
565 if unlikely!(b) {None} else {Some(a)}
568 /// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
573 /// This results in undefined behavior when
574 #[doc = concat!("`self * rhs > ", stringify!($SelfT), "::MAX` or `self * rhs < ", stringify!($SelfT), "::MIN`,")]
575 /// i.e. when [`checked_mul`] would return `None`.
577 #[doc = concat!("[`checked_mul`]: ", stringify!($SelfT), "::checked_mul")]
579 feature = "unchecked_math",
580 reason = "niche optimization path",
583 #[must_use = "this returns the result of the operation, \
584 without modifying the original"]
585 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
587 pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
588 // SAFETY: the caller must uphold the safety contract for
590 unsafe { intrinsics::unchecked_mul(self, rhs) }
593 /// Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
594 /// or the division results in overflow.
601 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 1).checked_div(-1), Some(", stringify!($Max), "));")]
602 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_div(-1), None);")]
603 #[doc = concat!("assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);")]
605 #[stable(feature = "rust1", since = "1.0.0")]
606 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.52.0")]
607 #[must_use = "this returns the result of the operation, \
608 without modifying the original"]
610 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
611 if unlikely!(rhs == 0 || ((self == Self::MIN) && (rhs == -1))) {
614 // SAFETY: div by zero and by INT_MIN have been checked above
615 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
619 /// Checked Euclidean division. Computes `self.div_euclid(rhs)`,
620 /// returning `None` if `rhs == 0` or the division results in overflow.
627 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 1).checked_div_euclid(-1), Some(", stringify!($Max), "));")]
628 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_div_euclid(-1), None);")]
629 #[doc = concat!("assert_eq!((1", stringify!($SelfT), ").checked_div_euclid(0), None);")]
631 #[stable(feature = "euclidean_division", since = "1.38.0")]
632 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
633 #[must_use = "this returns the result of the operation, \
634 without modifying the original"]
636 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
637 // Using `&` helps LLVM see that it is the same check made in division.
638 if unlikely!(rhs == 0 || ((self == Self::MIN) & (rhs == -1))) {
641 Some(self.div_euclid(rhs))
645 /// Checked integer remainder. Computes `self % rhs`, returning `None` if
646 /// `rhs == 0` or the division results in overflow.
654 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));")]
655 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);")]
656 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);")]
658 #[stable(feature = "wrapping", since = "1.7.0")]
659 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.52.0")]
660 #[must_use = "this returns the result of the operation, \
661 without modifying the original"]
663 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
664 if unlikely!(rhs == 0 || ((self == Self::MIN) && (rhs == -1))) {
667 // SAFETY: div by zero and by INT_MIN have been checked above
668 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
672 /// Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`
673 /// if `rhs == 0` or the division results in overflow.
680 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));")]
681 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);")]
682 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_rem_euclid(-1), None);")]
684 #[stable(feature = "euclidean_division", since = "1.38.0")]
685 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
686 #[must_use = "this returns the result of the operation, \
687 without modifying the original"]
689 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
690 // Using `&` helps LLVM see that it is the same check made in division.
691 if unlikely!(rhs == 0 || ((self == Self::MIN) & (rhs == -1))) {
694 Some(self.rem_euclid(rhs))
698 /// Checked negation. Computes `-self`, returning `None` if `self == MIN`.
706 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));")]
707 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);")]
709 #[stable(feature = "wrapping", since = "1.7.0")]
710 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
711 #[must_use = "this returns the result of the operation, \
712 without modifying the original"]
714 pub const fn checked_neg(self) -> Option<Self> {
715 let (a, b) = self.overflowing_neg();
716 if unlikely!(b) {None} else {Some(a)}
719 /// Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
720 /// than or equal to the number of bits in `self`.
727 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));")]
728 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);")]
730 #[stable(feature = "wrapping", since = "1.7.0")]
731 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
732 #[must_use = "this returns the result of the operation, \
733 without modifying the original"]
735 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
736 let (a, b) = self.overflowing_shl(rhs);
737 if unlikely!(b) {None} else {Some(a)}
740 /// Unchecked shift left. Computes `self << rhs`, assuming that
741 /// `rhs` is less than the number of bits in `self`.
745 /// This results in undefined behavior if `rhs` is larger than
746 /// or equal to the number of bits in `self`,
747 /// i.e. when [`checked_shl`] would return `None`.
749 #[doc = concat!("[`checked_shl`]: ", stringify!($SelfT), "::checked_shl")]
751 feature = "unchecked_math",
752 reason = "niche optimization path",
755 #[must_use = "this returns the result of the operation, \
756 without modifying the original"]
757 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
759 pub const unsafe fn unchecked_shl(self, rhs: Self) -> Self {
760 // SAFETY: the caller must uphold the safety contract for
762 unsafe { intrinsics::unchecked_shl(self, rhs) }
765 /// Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
766 /// larger than or equal to the number of bits in `self`.
773 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));")]
774 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);")]
776 #[stable(feature = "wrapping", since = "1.7.0")]
777 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
778 #[must_use = "this returns the result of the operation, \
779 without modifying the original"]
781 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
782 let (a, b) = self.overflowing_shr(rhs);
783 if unlikely!(b) {None} else {Some(a)}
786 /// Unchecked shift right. Computes `self >> rhs`, assuming that
787 /// `rhs` is less than the number of bits in `self`.
791 /// This results in undefined behavior if `rhs` is larger than
792 /// or equal to the number of bits in `self`,
793 /// i.e. when [`checked_shr`] would return `None`.
795 #[doc = concat!("[`checked_shr`]: ", stringify!($SelfT), "::checked_shr")]
797 feature = "unchecked_math",
798 reason = "niche optimization path",
801 #[must_use = "this returns the result of the operation, \
802 without modifying the original"]
803 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
805 pub const unsafe fn unchecked_shr(self, rhs: Self) -> Self {
806 // SAFETY: the caller must uphold the safety contract for
808 unsafe { intrinsics::unchecked_shr(self, rhs) }
811 /// Checked absolute value. Computes `self.abs()`, returning `None` if
820 #[doc = concat!("assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));")]
821 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);")]
823 #[stable(feature = "no_panic_abs", since = "1.13.0")]
824 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
825 #[must_use = "this returns the result of the operation, \
826 without modifying the original"]
828 pub const fn checked_abs(self) -> Option<Self> {
829 if self.is_negative() {
836 /// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
837 /// overflow occurred.
844 #[doc = concat!("assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));")]
845 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);")]
848 #[stable(feature = "no_panic_pow", since = "1.34.0")]
849 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
850 #[must_use = "this returns the result of the operation, \
851 without modifying the original"]
853 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
858 let mut acc: Self = 1;
862 acc = try_opt!(acc.checked_mul(base));
865 base = try_opt!(base.checked_mul(base));
867 // since exp!=0, finally the exp must be 1.
868 // Deal with the final bit of the exponent separately, since
869 // squaring the base afterwards is not necessary and may cause a
870 // needless overflow.
871 Some(try_opt!(acc.checked_mul(base)))
874 /// Saturating integer addition. Computes `self + rhs`, saturating at the numeric
875 /// bounds instead of overflowing.
882 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);")]
883 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(100), ", stringify!($SelfT), "::MAX);")]
884 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_add(-1), ", stringify!($SelfT), "::MIN);")]
887 #[stable(feature = "rust1", since = "1.0.0")]
888 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
889 #[must_use = "this returns the result of the operation, \
890 without modifying the original"]
892 pub const fn saturating_add(self, rhs: Self) -> Self {
893 intrinsics::saturating_add(self, rhs)
896 /// Saturating addition with an unsigned integer. Computes `self + rhs`,
897 /// saturating at the numeric bounds instead of overflowing.
904 /// # #![feature(mixed_integer_ops)]
905 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_unsigned(2), 3);")]
906 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add_unsigned(100), ", stringify!($SelfT), "::MAX);")]
908 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
909 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
910 #[must_use = "this returns the result of the operation, \
911 without modifying the original"]
913 pub const fn saturating_add_unsigned(self, rhs: $UnsignedT) -> Self {
914 // Overflow can only happen at the upper bound
915 // We cannot use `unwrap_or` here because it is not `const`
916 match self.checked_add_unsigned(rhs) {
922 /// Saturating integer subtraction. Computes `self - rhs`, saturating at the
923 /// numeric bounds instead of overflowing.
930 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);")]
931 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_sub(100), ", stringify!($SelfT), "::MIN);")]
932 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_sub(-1), ", stringify!($SelfT), "::MAX);")]
934 #[stable(feature = "rust1", since = "1.0.0")]
935 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
936 #[must_use = "this returns the result of the operation, \
937 without modifying the original"]
939 pub const fn saturating_sub(self, rhs: Self) -> Self {
940 intrinsics::saturating_sub(self, rhs)
943 /// Saturating subtraction with an unsigned integer. Computes `self - rhs`,
944 /// saturating at the numeric bounds instead of overflowing.
951 /// # #![feature(mixed_integer_ops)]
952 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_sub_unsigned(127), -27);")]
953 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_sub_unsigned(100), ", stringify!($SelfT), "::MIN);")]
955 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
956 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
957 #[must_use = "this returns the result of the operation, \
958 without modifying the original"]
960 pub const fn saturating_sub_unsigned(self, rhs: $UnsignedT) -> Self {
961 // Overflow can only happen at the lower bound
962 // We cannot use `unwrap_or` here because it is not `const`
963 match self.checked_sub_unsigned(rhs) {
969 /// Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
970 /// instead of overflowing.
977 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_neg(), -100);")]
978 #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").saturating_neg(), 100);")]
979 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_neg(), ", stringify!($SelfT), "::MAX);")]
980 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_neg(), ", stringify!($SelfT), "::MIN + 1);")]
983 #[stable(feature = "saturating_neg", since = "1.45.0")]
984 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
985 #[must_use = "this returns the result of the operation, \
986 without modifying the original"]
988 pub const fn saturating_neg(self) -> Self {
989 intrinsics::saturating_sub(0, self)
992 /// Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
993 /// MIN` instead of overflowing.
1000 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_abs(), 100);")]
1001 #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").saturating_abs(), 100);")]
1002 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_abs(), ", stringify!($SelfT), "::MAX);")]
1003 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 1).saturating_abs(), ", stringify!($SelfT), "::MAX);")]
1006 #[stable(feature = "saturating_neg", since = "1.45.0")]
1007 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1008 #[must_use = "this returns the result of the operation, \
1009 without modifying the original"]
1011 pub const fn saturating_abs(self) -> Self {
1012 if self.is_negative() {
1013 self.saturating_neg()
1019 /// Saturating integer multiplication. Computes `self * rhs`, saturating at the
1020 /// numeric bounds instead of overflowing.
1028 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);")]
1029 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);")]
1030 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);")]
1032 #[stable(feature = "wrapping", since = "1.7.0")]
1033 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1034 #[must_use = "this returns the result of the operation, \
1035 without modifying the original"]
1037 pub const fn saturating_mul(self, rhs: Self) -> Self {
1038 match self.checked_mul(rhs) {
1040 None => if (self < 0) == (rhs < 0) {
1048 /// Saturating integer division. Computes `self / rhs`, saturating at the
1049 /// numeric bounds instead of overflowing.
1056 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".saturating_div(2), 2);")]
1057 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_div(-1), ", stringify!($SelfT), "::MIN + 1);")]
1058 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_div(-1), ", stringify!($SelfT), "::MAX);")]
1063 #[doc = concat!("let _ = 1", stringify!($SelfT), ".saturating_div(0);")]
1066 #[stable(feature = "saturating_div", since = "1.58.0")]
1067 #[must_use = "this returns the result of the operation, \
1068 without modifying the original"]
1070 pub const fn saturating_div(self, rhs: Self) -> Self {
1071 match self.overflowing_div(rhs) {
1072 (result, false) => result,
1073 (_result, true) => Self::MAX, // MIN / -1 is the only possible saturating overflow
1077 /// Saturating integer exponentiation. Computes `self.pow(exp)`,
1078 /// saturating at the numeric bounds instead of overflowing.
1086 #[doc = concat!("assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);")]
1087 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);")]
1088 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);")]
1090 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1091 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1092 #[must_use = "this returns the result of the operation, \
1093 without modifying the original"]
1095 pub const fn saturating_pow(self, exp: u32) -> Self {
1096 match self.checked_pow(exp) {
1098 None if self < 0 && exp % 2 == 1 => Self::MIN,
1103 /// Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
1104 /// boundary of the type.
1111 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);")]
1112 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_add(2), ", stringify!($SelfT), "::MIN + 1);")]
1114 #[stable(feature = "rust1", since = "1.0.0")]
1115 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1116 #[must_use = "this returns the result of the operation, \
1117 without modifying the original"]
1119 pub const fn wrapping_add(self, rhs: Self) -> Self {
1120 intrinsics::wrapping_add(self, rhs)
1123 /// Wrapping (modular) addition with an unsigned integer. Computes
1124 /// `self + rhs`, wrapping around at the boundary of the type.
1131 /// # #![feature(mixed_integer_ops)]
1132 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_add_unsigned(27), 127);")]
1133 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_add_unsigned(2), ", stringify!($SelfT), "::MIN + 1);")]
1135 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1136 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1137 #[must_use = "this returns the result of the operation, \
1138 without modifying the original"]
1140 pub const fn wrapping_add_unsigned(self, rhs: $UnsignedT) -> Self {
1141 self.wrapping_add(rhs as Self)
1144 /// Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1145 /// boundary of the type.
1152 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);")]
1153 #[doc = concat!("assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::MAX), ", stringify!($SelfT), "::MAX);")]
1155 #[stable(feature = "rust1", since = "1.0.0")]
1156 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1157 #[must_use = "this returns the result of the operation, \
1158 without modifying the original"]
1160 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1161 intrinsics::wrapping_sub(self, rhs)
1164 /// Wrapping (modular) subtraction with an unsigned integer. Computes
1165 /// `self - rhs`, wrapping around at the boundary of the type.
1172 /// # #![feature(mixed_integer_ops)]
1173 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".wrapping_sub_unsigned(127), -127);")]
1174 #[doc = concat!("assert_eq!((-2", stringify!($SelfT), ").wrapping_sub_unsigned(", stringify!($UnsignedT), "::MAX), -1);")]
1176 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1177 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1178 #[must_use = "this returns the result of the operation, \
1179 without modifying the original"]
1181 pub const fn wrapping_sub_unsigned(self, rhs: $UnsignedT) -> Self {
1182 self.wrapping_sub(rhs as Self)
1185 /// Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1186 /// the boundary of the type.
1193 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);")]
1194 /// assert_eq!(11i8.wrapping_mul(12), -124);
1196 #[stable(feature = "rust1", since = "1.0.0")]
1197 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1198 #[must_use = "this returns the result of the operation, \
1199 without modifying the original"]
1201 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1202 intrinsics::wrapping_mul(self, rhs)
1205 /// Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1206 /// boundary of the type.
1208 /// The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1209 /// `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1210 /// that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1214 /// This function will panic if `rhs` is 0.
1221 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);")]
1222 /// assert_eq!((-128i8).wrapping_div(-1), -128);
1224 #[stable(feature = "num_wrapping", since = "1.2.0")]
1225 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1226 #[must_use = "this returns the result of the operation, \
1227 without modifying the original"]
1229 pub const fn wrapping_div(self, rhs: Self) -> Self {
1230 self.overflowing_div(rhs).0
1233 /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
1234 /// wrapping around at the boundary of the type.
1236 /// Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1237 /// for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1238 /// type. In this case, this method returns `MIN` itself.
1242 /// This function will panic if `rhs` is 0.
1249 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);")]
1250 /// assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
1252 #[stable(feature = "euclidean_division", since = "1.38.0")]
1253 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1254 #[must_use = "this returns the result of the operation, \
1255 without modifying the original"]
1257 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
1258 self.overflowing_div_euclid(rhs).0
1261 /// Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1262 /// boundary of the type.
1264 /// Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1265 /// invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1266 /// this function returns `0`.
1270 /// This function will panic if `rhs` is 0.
1277 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);")]
1278 /// assert_eq!((-128i8).wrapping_rem(-1), 0);
1280 #[stable(feature = "num_wrapping", since = "1.2.0")]
1281 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1282 #[must_use = "this returns the result of the operation, \
1283 without modifying the original"]
1285 pub const fn wrapping_rem(self, rhs: Self) -> Self {
1286 self.overflowing_rem(rhs).0
1289 /// Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
1290 /// at the boundary of the type.
1292 /// Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1293 /// for the type). In this case, this method returns 0.
1297 /// This function will panic if `rhs` is 0.
1304 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);")]
1305 /// assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
1307 #[stable(feature = "euclidean_division", since = "1.38.0")]
1308 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1309 #[must_use = "this returns the result of the operation, \
1310 without modifying the original"]
1312 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1313 self.overflowing_rem_euclid(rhs).0
1316 /// Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1319 /// The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1320 /// is the negative minimal value for the type); this is a positive value that is too large to represent
1321 /// in the type. In such a case, this function returns `MIN` itself.
1328 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);")]
1329 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.wrapping_neg(), ", stringify!($SelfT), "::MIN);")]
1331 #[stable(feature = "num_wrapping", since = "1.2.0")]
1332 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1333 #[must_use = "this returns the result of the operation, \
1334 without modifying the original"]
1336 pub const fn wrapping_neg(self) -> Self {
1337 (0 as $SelfT).wrapping_sub(self)
1340 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1341 /// any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1343 /// Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1344 /// the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1345 /// The primitive integer types all implement a [`rotate_left`](Self::rotate_left) function,
1346 /// which may be what you want instead.
1353 #[doc = concat!("assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);")]
1354 #[doc = concat!("assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);")]
1356 #[stable(feature = "num_wrapping", since = "1.2.0")]
1357 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1358 #[must_use = "this returns the result of the operation, \
1359 without modifying the original"]
1361 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1362 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1365 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1369 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1370 /// removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1372 /// Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1373 /// to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1374 /// end. The primitive integer types all implement a [`rotate_right`](Self::rotate_right) function,
1375 /// which may be what you want instead.
1382 #[doc = concat!("assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);")]
1383 /// assert_eq!((-128i16).wrapping_shr(64), -128);
1385 #[stable(feature = "num_wrapping", since = "1.2.0")]
1386 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1387 #[must_use = "this returns the result of the operation, \
1388 without modifying the original"]
1390 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1391 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1394 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1398 /// Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1399 /// the boundary of the type.
1401 /// The only case where such wrapping can occur is when one takes the absolute value of the negative
1402 /// minimal value for the type; this is a positive value that is too large to represent in the type. In
1403 /// such a case, this function returns `MIN` itself.
1410 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);")]
1411 #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);")]
1412 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.wrapping_abs(), ", stringify!($SelfT), "::MIN);")]
1413 /// assert_eq!((-128i8).wrapping_abs() as u8, 128);
1415 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1416 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1417 #[must_use = "this returns the result of the operation, \
1418 without modifying the original"]
1419 #[allow(unused_attributes)]
1421 pub const fn wrapping_abs(self) -> Self {
1422 if self.is_negative() {
1429 /// Computes the absolute value of `self` without any wrapping
1438 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".unsigned_abs(), 100", stringify!($UnsignedT), ");")]
1439 #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").unsigned_abs(), 100", stringify!($UnsignedT), ");")]
1440 /// assert_eq!((-128i8).unsigned_abs(), 128u8);
1442 #[stable(feature = "unsigned_abs", since = "1.51.0")]
1443 #[rustc_const_stable(feature = "unsigned_abs", since = "1.51.0")]
1444 #[must_use = "this returns the result of the operation, \
1445 without modifying the original"]
1447 pub const fn unsigned_abs(self) -> $UnsignedT {
1448 self.wrapping_abs() as $UnsignedT
1451 /// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1452 /// wrapping around at the boundary of the type.
1459 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);")]
1460 /// assert_eq!(3i8.wrapping_pow(5), -13);
1461 /// assert_eq!(3i8.wrapping_pow(6), -39);
1463 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1464 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1465 #[must_use = "this returns the result of the operation, \
1466 without modifying the original"]
1468 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
1472 let mut base = self;
1473 let mut acc: Self = 1;
1477 acc = acc.wrapping_mul(base);
1480 base = base.wrapping_mul(base);
1483 // since exp!=0, finally the exp must be 1.
1484 // Deal with the final bit of the exponent separately, since
1485 // squaring the base afterwards is not necessary and may cause a
1486 // needless overflow.
1487 acc.wrapping_mul(base)
1490 /// Calculates `self` + `rhs`
1492 /// Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1493 /// occur. If an overflow would have occurred then the wrapped value is returned.
1501 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));")]
1502 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT), "::MIN, true));")]
1504 #[stable(feature = "wrapping", since = "1.7.0")]
1505 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1506 #[must_use = "this returns the result of the operation, \
1507 without modifying the original"]
1509 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1510 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1514 /// Calculates `self` + `rhs` with an unsigned `rhs`
1516 /// Returns a tuple of the addition along with a boolean indicating
1517 /// whether an arithmetic overflow would occur. If an overflow would
1518 /// have occurred then the wrapped value is returned.
1525 /// # #![feature(mixed_integer_ops)]
1526 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_unsigned(2), (3, false));")]
1527 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN).overflowing_add_unsigned(", stringify!($UnsignedT), "::MAX), (", stringify!($SelfT), "::MAX, false));")]
1528 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).overflowing_add_unsigned(3), (", stringify!($SelfT), "::MIN, true));")]
1530 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1531 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1532 #[must_use = "this returns the result of the operation, \
1533 without modifying the original"]
1535 pub const fn overflowing_add_unsigned(self, rhs: $UnsignedT) -> (Self, bool) {
1536 let rhs = rhs as Self;
1537 let (res, overflowed) = self.overflowing_add(rhs);
1538 (res, overflowed ^ (rhs < 0))
1541 /// Calculates `self` - `rhs`
1543 /// Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1544 /// would occur. If an overflow would have occurred then the wrapped value is returned.
1552 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));")]
1553 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")]
1555 #[stable(feature = "wrapping", since = "1.7.0")]
1556 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1557 #[must_use = "this returns the result of the operation, \
1558 without modifying the original"]
1560 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1561 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1565 /// Calculates `self` - `rhs` with an unsigned `rhs`
1567 /// Returns a tuple of the subtraction along with a boolean indicating
1568 /// whether an arithmetic overflow would occur. If an overflow would
1569 /// have occurred then the wrapped value is returned.
1576 /// # #![feature(mixed_integer_ops)]
1577 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_sub_unsigned(2), (-1, false));")]
1578 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX).overflowing_sub_unsigned(", stringify!($UnsignedT), "::MAX), (", stringify!($SelfT), "::MIN, false));")]
1579 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 2).overflowing_sub_unsigned(3), (", stringify!($SelfT), "::MAX, true));")]
1581 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1582 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1583 #[must_use = "this returns the result of the operation, \
1584 without modifying the original"]
1586 pub const fn overflowing_sub_unsigned(self, rhs: $UnsignedT) -> (Self, bool) {
1587 let rhs = rhs as Self;
1588 let (res, overflowed) = self.overflowing_sub(rhs);
1589 (res, overflowed ^ (rhs < 0))
1592 /// Calculates the multiplication of `self` and `rhs`.
1594 /// Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1595 /// would occur. If an overflow would have occurred then the wrapped value is returned.
1602 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));")]
1603 /// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
1605 #[stable(feature = "wrapping", since = "1.7.0")]
1606 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1607 #[must_use = "this returns the result of the operation, \
1608 without modifying the original"]
1610 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1611 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1615 /// Calculates the divisor when `self` is divided by `rhs`.
1617 /// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1618 /// occur. If an overflow would occur then self is returned.
1622 /// This function will panic if `rhs` is 0.
1630 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));")]
1631 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT), "::MIN, true));")]
1634 #[stable(feature = "wrapping", since = "1.7.0")]
1635 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1636 #[must_use = "this returns the result of the operation, \
1637 without modifying the original"]
1638 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1639 // Using `&` helps LLVM see that it is the same check made in division.
1640 if unlikely!((self == Self::MIN) & (rhs == -1)) {
1647 /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1649 /// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1650 /// occur. If an overflow would occur then `self` is returned.
1654 /// This function will panic if `rhs` is 0.
1661 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));")]
1662 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euclid(-1), (", stringify!($SelfT), "::MIN, true));")]
1665 #[stable(feature = "euclidean_division", since = "1.38.0")]
1666 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1667 #[must_use = "this returns the result of the operation, \
1668 without modifying the original"]
1669 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1670 // Using `&` helps LLVM see that it is the same check made in division.
1671 if unlikely!((self == Self::MIN) & (rhs == -1)) {
1674 (self.div_euclid(rhs), false)
1678 /// Calculates the remainder when `self` is divided by `rhs`.
1680 /// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1681 /// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1685 /// This function will panic if `rhs` is 0.
1693 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));")]
1694 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));")]
1697 #[stable(feature = "wrapping", since = "1.7.0")]
1698 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1699 #[must_use = "this returns the result of the operation, \
1700 without modifying the original"]
1701 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1702 if unlikely!(rhs == -1) {
1703 (0, self == Self::MIN)
1710 /// Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
1712 /// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1713 /// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1717 /// This function will panic if `rhs` is 0.
1724 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));")]
1725 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem_euclid(-1), (0, true));")]
1727 #[stable(feature = "euclidean_division", since = "1.38.0")]
1728 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1729 #[must_use = "this returns the result of the operation, \
1730 without modifying the original"]
1732 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1733 if unlikely!(rhs == -1) {
1734 (0, self == Self::MIN)
1736 (self.rem_euclid(rhs), false)
1741 /// Negates self, overflowing if this is equal to the minimum value.
1743 /// Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1744 /// happened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the
1745 /// minimum value will be returned again and `true` will be returned for an overflow happening.
1752 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));")]
1753 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT), "::MIN, true));")]
1756 #[stable(feature = "wrapping", since = "1.7.0")]
1757 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1758 #[must_use = "this returns the result of the operation, \
1759 without modifying the original"]
1760 #[allow(unused_attributes)]
1761 pub const fn overflowing_neg(self) -> (Self, bool) {
1762 if unlikely!(self == Self::MIN) {
1769 /// Shifts self left by `rhs` bits.
1771 /// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1772 /// value was larger than or equal to the number of bits. If the shift value is too large, then value is
1773 /// masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1780 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));")]
1781 /// assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));
1783 #[stable(feature = "wrapping", since = "1.7.0")]
1784 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1785 #[must_use = "this returns the result of the operation, \
1786 without modifying the original"]
1788 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1789 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1792 /// Shifts self right by `rhs` bits.
1794 /// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1795 /// value was larger than or equal to the number of bits. If the shift value is too large, then value is
1796 /// masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1803 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));")]
1804 /// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
1806 #[stable(feature = "wrapping", since = "1.7.0")]
1807 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1808 #[must_use = "this returns the result of the operation, \
1809 without modifying the original"]
1811 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1812 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1815 /// Computes the absolute value of `self`.
1817 /// Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1818 /// happened. If self is the minimum value
1819 #[doc = concat!("(e.g., ", stringify!($SelfT), "::MIN for values of type ", stringify!($SelfT), "),")]
1820 /// then the minimum value will be returned again and true will be returned
1821 /// for an overflow happening.
1828 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));")]
1829 #[doc = concat!("assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));")]
1830 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN).overflowing_abs(), (", stringify!($SelfT), "::MIN, true));")]
1832 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1833 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1834 #[must_use = "this returns the result of the operation, \
1835 without modifying the original"]
1837 pub const fn overflowing_abs(self) -> (Self, bool) {
1838 (self.wrapping_abs(), self == Self::MIN)
1841 /// Raises self to the power of `exp`, using exponentiation by squaring.
1843 /// Returns a tuple of the exponentiation along with a bool indicating
1844 /// whether an overflow happened.
1851 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));")]
1852 /// assert_eq!(3i8.overflowing_pow(5), (-13, true));
1854 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1855 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1856 #[must_use = "this returns the result of the operation, \
1857 without modifying the original"]
1859 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1863 let mut base = self;
1864 let mut acc: Self = 1;
1865 let mut overflown = false;
1866 // Scratch space for storing results of overflowing_mul.
1871 r = acc.overflowing_mul(base);
1876 r = base.overflowing_mul(base);
1881 // since exp!=0, finally the exp must be 1.
1882 // Deal with the final bit of the exponent separately, since
1883 // squaring the base afterwards is not necessary and may cause a
1884 // needless overflow.
1885 r = acc.overflowing_mul(base);
1890 /// Raises self to the power of `exp`, using exponentiation by squaring.
1897 #[doc = concat!("let x: ", stringify!($SelfT), " = 2; // or any other integer type")]
1899 /// assert_eq!(x.pow(5), 32);
1901 #[stable(feature = "rust1", since = "1.0.0")]
1902 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1903 #[must_use = "this returns the result of the operation, \
1904 without modifying the original"]
1906 #[rustc_inherit_overflow_checks]
1907 pub const fn pow(self, mut exp: u32) -> Self {
1911 let mut base = self;
1922 // since exp!=0, finally the exp must be 1.
1923 // Deal with the final bit of the exponent separately, since
1924 // squaring the base afterwards is not necessary and may cause a
1925 // needless overflow.
1929 /// Calculates the quotient of Euclidean division of `self` by `rhs`.
1931 /// This computes the integer `q` such that `self = q * rhs + r`, with
1932 /// `r = self.rem_euclid(rhs)` and `0 <= r < abs(rhs)`.
1934 /// In other words, the result is `self / rhs` rounded to the integer `q`
1935 /// such that `self >= q * rhs`.
1936 /// If `self > 0`, this is equal to round towards zero (the default in Rust);
1937 /// if `self < 0`, this is equal to round towards +/- infinity.
1941 /// This function will panic if `rhs` is 0 or the division results in overflow.
1948 #[doc = concat!("let a: ", stringify!($SelfT), " = 7; // or any other integer type")]
1951 /// assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
1952 /// assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
1953 /// assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
1954 /// assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
1956 #[stable(feature = "euclidean_division", since = "1.38.0")]
1957 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1958 #[must_use = "this returns the result of the operation, \
1959 without modifying the original"]
1961 #[rustc_inherit_overflow_checks]
1962 pub const fn div_euclid(self, rhs: Self) -> Self {
1965 return if rhs > 0 { q - 1 } else { q + 1 }
1971 /// Calculates the least nonnegative remainder of `self (mod rhs)`.
1973 /// This is done as if by the Euclidean division algorithm -- given
1974 /// `r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) + r`, and
1975 /// `0 <= r < abs(rhs)`.
1979 /// This function will panic if `rhs` is 0 or the division results in overflow.
1986 #[doc = concat!("let a: ", stringify!($SelfT), " = 7; // or any other integer type")]
1989 /// assert_eq!(a.rem_euclid(b), 3);
1990 /// assert_eq!((-a).rem_euclid(b), 1);
1991 /// assert_eq!(a.rem_euclid(-b), 3);
1992 /// assert_eq!((-a).rem_euclid(-b), 1);
1994 #[stable(feature = "euclidean_division", since = "1.38.0")]
1995 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1996 #[must_use = "this returns the result of the operation, \
1997 without modifying the original"]
1999 #[rustc_inherit_overflow_checks]
2000 pub const fn rem_euclid(self, rhs: Self) -> Self {
2013 /// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
2017 /// This function will panic if `rhs` is 0 or the division results in overflow.
2024 /// #![feature(int_roundings)]
2025 #[doc = concat!("let a: ", stringify!($SelfT)," = 8;")]
2028 /// assert_eq!(a.div_floor(b), 2);
2029 /// assert_eq!(a.div_floor(-b), -3);
2030 /// assert_eq!((-a).div_floor(b), -3);
2031 /// assert_eq!((-a).div_floor(-b), 2);
2033 #[unstable(feature = "int_roundings", issue = "88581")]
2034 #[must_use = "this returns the result of the operation, \
2035 without modifying the original"]
2037 #[rustc_inherit_overflow_checks]
2038 pub const fn div_floor(self, rhs: Self) -> Self {
2041 if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) {
2048 /// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
2052 /// This function will panic if `rhs` is 0 or the division results in overflow.
2059 /// #![feature(int_roundings)]
2060 #[doc = concat!("let a: ", stringify!($SelfT)," = 8;")]
2063 /// assert_eq!(a.div_ceil(b), 3);
2064 /// assert_eq!(a.div_ceil(-b), -2);
2065 /// assert_eq!((-a).div_ceil(b), -2);
2066 /// assert_eq!((-a).div_ceil(-b), 3);
2068 #[unstable(feature = "int_roundings", issue = "88581")]
2069 #[must_use = "this returns the result of the operation, \
2070 without modifying the original"]
2072 #[rustc_inherit_overflow_checks]
2073 pub const fn div_ceil(self, rhs: Self) -> Self {
2076 if (r > 0 && rhs > 0) || (r < 0 && rhs < 0) {
2083 /// If `rhs` is positive, calculates the smallest value greater than or
2084 /// equal to `self` that is a multiple of `rhs`. If `rhs` is negative,
2085 /// calculates the largest value less than or equal to `self` that is a
2086 /// multiple of `rhs`.
2090 /// This function will panic if `rhs` is 0 or the operation results in overflow.
2097 /// #![feature(int_roundings)]
2098 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".next_multiple_of(8), 16);")]
2099 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".next_multiple_of(8), 24);")]
2100 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".next_multiple_of(-8), 16);")]
2101 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".next_multiple_of(-8), 16);")]
2102 #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").next_multiple_of(8), -16);")]
2103 #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").next_multiple_of(8), -16);")]
2104 #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").next_multiple_of(-8), -16);")]
2105 #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").next_multiple_of(-8), -24);")]
2107 #[unstable(feature = "int_roundings", issue = "88581")]
2108 #[must_use = "this returns the result of the operation, \
2109 without modifying the original"]
2111 #[rustc_inherit_overflow_checks]
2112 pub const fn next_multiple_of(self, rhs: Self) -> Self {
2113 // This would otherwise fail when calculating `r` when self == T::MIN.
2119 let m = if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) {
2132 /// If `rhs` is positive, calculates the smallest value greater than or
2133 /// equal to `self` that is a multiple of `rhs`. If `rhs` is negative,
2134 /// calculates the largest value less than or equal to `self` that is a
2135 /// multiple of `rhs`. Returns `None` if `rhs` is zero or the operation
2136 /// would result in overflow.
2143 /// #![feature(int_roundings)]
2144 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(16));")]
2145 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(24));")]
2146 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(-8), Some(16));")]
2147 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(-8), Some(16));")]
2148 #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").checked_next_multiple_of(8), Some(-16));")]
2149 #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").checked_next_multiple_of(8), Some(-16));")]
2150 #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").checked_next_multiple_of(-8), Some(-16));")]
2151 #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").checked_next_multiple_of(-8), Some(-24));")]
2152 #[doc = concat!("assert_eq!(1_", stringify!($SelfT), ".checked_next_multiple_of(0), None);")]
2153 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_multiple_of(2), None);")]
2155 #[unstable(feature = "int_roundings", issue = "88581")]
2156 #[must_use = "this returns the result of the operation, \
2157 without modifying the original"]
2159 #[rustc_inherit_overflow_checks]
2160 pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
2161 // This would otherwise fail when calculating `r` when self == T::MIN.
2166 let r = try_opt!(self.checked_rem(rhs));
2167 let m = if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) {
2168 try_opt!(r.checked_add(rhs))
2176 self.checked_add(try_opt!(rhs.checked_sub(m)))
2180 /// Returns the logarithm of the number with respect to an arbitrary base,
2183 /// This method might not be optimized owing to implementation details;
2184 /// `log2` can produce results more efficiently for base 2, and `log10`
2185 /// can produce results more efficiently for base 10.
2189 /// When the number is zero, or if the base is not at least 2; it
2190 /// panics in debug mode and the return value is 0 in release
2196 /// #![feature(int_log)]
2197 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".log(5), 1);")]
2199 #[unstable(feature = "int_log", issue = "70887")]
2200 #[must_use = "this returns the result of the operation, \
2201 without modifying the original"]
2204 #[rustc_inherit_overflow_checks]
2205 #[allow(arithmetic_overflow)]
2206 pub const fn log(self, base: Self) -> u32 {
2207 match self.checked_log(base) {
2210 // In debug builds, trigger a panic on None.
2211 // This should optimize completely out in release builds.
2212 let _ = Self::MAX + 1;
2219 /// Returns the base 2 logarithm of the number, rounded down.
2223 /// When the number is zero it panics in debug mode and the return value
2224 /// is 0 in release mode.
2229 /// #![feature(int_log)]
2230 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".log2(), 1);")]
2232 #[unstable(feature = "int_log", issue = "70887")]
2233 #[must_use = "this returns the result of the operation, \
2234 without modifying the original"]
2237 #[rustc_inherit_overflow_checks]
2238 #[allow(arithmetic_overflow)]
2239 pub const fn log2(self) -> u32 {
2240 match self.checked_log2() {
2243 // In debug builds, trigger a panic on None.
2244 // This should optimize completely out in release builds.
2245 let _ = Self::MAX + 1;
2252 /// Returns the base 10 logarithm of the number, rounded down.
2256 /// When the number is zero it panics in debug mode and the return value
2257 /// is 0 in release mode.
2262 /// #![feature(int_log)]
2263 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".log10(), 1);")]
2265 #[unstable(feature = "int_log", issue = "70887")]
2266 #[must_use = "this returns the result of the operation, \
2267 without modifying the original"]
2270 #[rustc_inherit_overflow_checks]
2271 #[allow(arithmetic_overflow)]
2272 pub const fn log10(self) -> u32 {
2273 match self.checked_log10() {
2276 // In debug builds, trigger a panic on None.
2277 // This should optimize completely out in release builds.
2278 let _ = Self::MAX + 1;
2285 /// Returns the logarithm of the number with respect to an arbitrary base,
2288 /// Returns `None` if the number is negative or zero, or if the base is not at least 2.
2290 /// This method might not be optimized owing to implementation details;
2291 /// `checked_log2` can produce results more efficiently for base 2, and
2292 /// `checked_log10` can produce results more efficiently for base 10.
2297 /// #![feature(int_log)]
2298 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_log(5), Some(1));")]
2300 #[unstable(feature = "int_log", issue = "70887")]
2301 #[must_use = "this returns the result of the operation, \
2302 without modifying the original"]
2304 pub const fn checked_log(self, base: Self) -> Option<u32> {
2305 if self <= 0 || base <= 1 {
2311 // Optimization for 128 bit wide integers.
2312 if Self::BITS == 128 {
2313 let b = Self::log2(self) / (Self::log2(base) + 1);
2315 r /= base.pow(b as u32);
2326 /// Returns the base 2 logarithm of the number, rounded down.
2328 /// Returns `None` if the number is negative or zero.
2333 /// #![feature(int_log)]
2334 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_log2(), Some(1));")]
2336 #[unstable(feature = "int_log", issue = "70887")]
2337 #[must_use = "this returns the result of the operation, \
2338 without modifying the original"]
2340 pub const fn checked_log2(self) -> Option<u32> {
2344 // SAFETY: We just checked that this number is positive
2345 let log = (Self::BITS - 1) - unsafe { intrinsics::ctlz_nonzero(self) as u32 };
2350 /// Returns the base 10 logarithm of the number, rounded down.
2352 /// Returns `None` if the number is negative or zero.
2357 /// #![feature(int_log)]
2358 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_log10(), Some(1));")]
2360 #[unstable(feature = "int_log", issue = "70887")]
2361 #[must_use = "this returns the result of the operation, \
2362 without modifying the original"]
2364 pub const fn checked_log10(self) -> Option<u32> {
2366 Some(int_log10::$ActualT(self as $ActualT))
2372 /// Computes the absolute value of `self`.
2374 /// # Overflow behavior
2376 /// The absolute value of
2377 #[doc = concat!("`", stringify!($SelfT), "::MIN`")]
2378 /// cannot be represented as an
2379 #[doc = concat!("`", stringify!($SelfT), "`,")]
2380 /// and attempting to calculate it will cause an overflow. This means
2381 /// that code in debug mode will trigger a panic on this case and
2382 /// optimized code will return
2383 #[doc = concat!("`", stringify!($SelfT), "::MIN`")]
2384 /// without a panic.
2391 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".abs(), 10);")]
2392 #[doc = concat!("assert_eq!((-10", stringify!($SelfT), ").abs(), 10);")]
2394 #[stable(feature = "rust1", since = "1.0.0")]
2395 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2396 #[allow(unused_attributes)]
2397 #[must_use = "this returns the result of the operation, \
2398 without modifying the original"]
2400 #[rustc_inherit_overflow_checks]
2401 pub const fn abs(self) -> Self {
2402 // Note that the #[rustc_inherit_overflow_checks] and #[inline]
2403 // above mean that the overflow semantics of the subtraction
2404 // depend on the crate we're being called from.
2405 if self.is_negative() {
2412 /// Computes the absolute difference between `self` and `other`.
2414 /// This function always returns the correct answer without overflow or
2415 /// panics by returning an unsigned integer.
2422 /// #![feature(int_abs_diff)]
2423 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(80), 20", stringify!($UnsignedT), ");")]
2424 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(110), 10", stringify!($UnsignedT), ");")]
2425 #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").abs_diff(80), 180", stringify!($UnsignedT), ");")]
2426 #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").abs_diff(-120), 20", stringify!($UnsignedT), ");")]
2427 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.abs_diff(", stringify!($SelfT), "::MAX), ", stringify!($UnsignedT), "::MAX);")]
2429 #[unstable(feature = "int_abs_diff", issue = "89492")]
2430 #[must_use = "this returns the result of the operation, \
2431 without modifying the original"]
2433 pub const fn abs_diff(self, other: Self) -> $UnsignedT {
2435 // Converting a non-negative x from signed to unsigned by using
2436 // `x as U` is left unchanged, but a negative x is converted
2437 // to value x + 2^N. Thus if `s` and `o` are binary variables
2438 // respectively indicating whether `self` and `other` are
2439 // negative, we are computing the mathematical value:
2441 // (other + o*2^N) - (self + s*2^N) mod 2^N
2442 // other - self + (o-s)*2^N mod 2^N
2443 // other - self mod 2^N
2445 // Finally, taking the mod 2^N of the mathematical value of
2446 // `other - self` does not change it as it already is
2447 // in the range [0, 2^N).
2448 (other as $UnsignedT).wrapping_sub(self as $UnsignedT)
2450 (self as $UnsignedT).wrapping_sub(other as $UnsignedT)
2454 /// Returns a number representing sign of `self`.
2456 /// - `0` if the number is zero
2457 /// - `1` if the number is positive
2458 /// - `-1` if the number is negative
2465 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".signum(), 1);")]
2466 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".signum(), 0);")]
2467 #[doc = concat!("assert_eq!((-10", stringify!($SelfT), ").signum(), -1);")]
2469 #[stable(feature = "rust1", since = "1.0.0")]
2470 #[rustc_const_stable(feature = "const_int_sign", since = "1.47.0")]
2471 #[must_use = "this returns the result of the operation, \
2472 without modifying the original"]
2474 pub const fn signum(self) -> Self {
2482 /// Returns `true` if `self` is positive and `false` if the number is zero or
2490 #[doc = concat!("assert!(10", stringify!($SelfT), ".is_positive());")]
2491 #[doc = concat!("assert!(!(-10", stringify!($SelfT), ").is_positive());")]
2494 #[stable(feature = "rust1", since = "1.0.0")]
2495 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2497 pub const fn is_positive(self) -> bool { self > 0 }
2499 /// Returns `true` if `self` is negative and `false` if the number is zero or
2507 #[doc = concat!("assert!((-10", stringify!($SelfT), ").is_negative());")]
2508 #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_negative());")]
2511 #[stable(feature = "rust1", since = "1.0.0")]
2512 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2514 pub const fn is_negative(self) -> bool { self < 0 }
2516 /// Return the memory representation of this integer as a byte array in
2517 /// big-endian (network) byte order.
2519 #[doc = $to_xe_bytes_doc]
2524 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();")]
2525 #[doc = concat!("assert_eq!(bytes, ", $be_bytes, ");")]
2527 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2528 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2529 #[must_use = "this returns the result of the operation, \
2530 without modifying the original"]
2532 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2533 self.to_be().to_ne_bytes()
2536 /// Return the memory representation of this integer as a byte array in
2537 /// little-endian byte order.
2539 #[doc = $to_xe_bytes_doc]
2544 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();")]
2545 #[doc = concat!("assert_eq!(bytes, ", $le_bytes, ");")]
2547 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2548 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2549 #[must_use = "this returns the result of the operation, \
2550 without modifying the original"]
2552 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2553 self.to_le().to_ne_bytes()
2556 /// Return the memory representation of this integer as a byte array in
2557 /// native byte order.
2559 /// As the target platform's native endianness is used, portable code
2560 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2563 #[doc = $to_xe_bytes_doc]
2565 /// [`to_be_bytes`]: Self::to_be_bytes
2566 /// [`to_le_bytes`]: Self::to_le_bytes
2571 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();")]
2574 /// if cfg!(target_endian = "big") {
2575 #[doc = concat!(" ", $be_bytes)]
2577 #[doc = concat!(" ", $le_bytes)]
2581 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2582 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2583 // SAFETY: const sound because integers are plain old datatypes so we can always
2584 // transmute them to arrays of bytes
2585 #[must_use = "this returns the result of the operation, \
2586 without modifying the original"]
2588 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2589 // SAFETY: integers are plain old datatypes so we can always transmute them to
2591 unsafe { mem::transmute(self) }
2594 /// Create an integer value from its representation as a byte array in
2597 #[doc = $to_xe_bytes_doc]
2602 #[doc = concat!("let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");")]
2603 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2606 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2609 #[doc = concat!("fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2610 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2612 #[doc = concat!(" ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())")]
2615 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2616 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2619 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2620 Self::from_be(Self::from_ne_bytes(bytes))
2623 /// Create an integer value from its representation as a byte array in
2626 #[doc = $to_xe_bytes_doc]
2631 #[doc = concat!("let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");")]
2632 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2635 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2638 #[doc = concat!("fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2639 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2641 #[doc = concat!(" ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())")]
2644 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2645 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2648 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2649 Self::from_le(Self::from_ne_bytes(bytes))
2652 /// Create an integer value from its memory representation as a byte
2653 /// array in native endianness.
2655 /// As the target platform's native endianness is used, portable code
2656 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2657 /// appropriate instead.
2659 /// [`from_be_bytes`]: Self::from_be_bytes
2660 /// [`from_le_bytes`]: Self::from_le_bytes
2662 #[doc = $to_xe_bytes_doc]
2667 #[doc = concat!("let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {")]
2668 #[doc = concat!(" ", $be_bytes)]
2670 #[doc = concat!(" ", $le_bytes)]
2672 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2675 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2678 #[doc = concat!("fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2679 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2681 #[doc = concat!(" ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())")]
2684 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2685 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2687 // SAFETY: const sound because integers are plain old datatypes so we can always
2688 // transmute to them
2690 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2691 // SAFETY: integers are plain old datatypes so we can always transmute to them
2692 unsafe { mem::transmute(bytes) }
2695 /// New code should prefer to use
2696 #[doc = concat!("[`", stringify!($SelfT), "::MIN", "`] instead.")]
2698 /// Returns the smallest value that can be represented by this integer type.
2699 #[stable(feature = "rust1", since = "1.0.0")]
2702 #[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
2703 #[rustc_deprecated(since = "TBD", reason = "replaced by the `MIN` associated constant on this type")]
2704 pub const fn min_value() -> Self {
2708 /// New code should prefer to use
2709 #[doc = concat!("[`", stringify!($SelfT), "::MAX", "`] instead.")]
2711 /// Returns the largest value that can be represented by this integer type.
2712 #[stable(feature = "rust1", since = "1.0.0")]
2715 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2716 #[rustc_deprecated(since = "TBD", reason = "replaced by the `MAX` associated constant on this type")]
2717 pub const fn max_value() -> Self {