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 $bound_condition:expr) => {
7 /// The smallest value that can be represented by this integer type
8 #[doc = concat!("(−2<sup>", $BITS_MINUS_ONE, "</sup>", $bound_condition, ")")]
15 #[doc = concat!("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;
20 /// The largest value that can be represented by this integer type
21 #[doc = concat!("(2<sup>", $BITS_MINUS_ONE, "</sup> − 1", $bound_condition, ")")]
28 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($Max), ");")]
30 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
31 pub const MAX: Self = !Self::MIN;
33 /// The size of this integer type in bits.
38 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::BITS, ", stringify!($BITS), ");")]
40 #[stable(feature = "int_bits_const", since = "1.53.0")]
41 pub const BITS: u32 = $BITS;
43 /// Converts a string slice in a given base to an integer.
45 /// The string is expected to be an optional `+` or `-` sign followed by digits.
46 /// Leading and trailing whitespace represent an error. Digits are a subset of these characters,
47 /// depending on `radix`:
55 /// This function panics if `radix` is not in the range from 2 to 36.
62 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));")]
64 #[stable(feature = "rust1", since = "1.0.0")]
65 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
66 from_str_radix(src, radix)
69 /// Returns the number of ones in the binary representation of `self`.
76 #[doc = concat!("let n = 0b100_0000", stringify!($SelfT), ";")]
78 /// assert_eq!(n.count_ones(), 1);
81 #[stable(feature = "rust1", since = "1.0.0")]
82 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
83 #[doc(alias = "popcount")]
84 #[doc(alias = "popcnt")]
85 #[must_use = "this returns the result of the operation, \
86 without modifying the original"]
88 pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
90 /// Returns the number of zeros in the binary representation of `self`.
97 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.count_zeros(), 1);")]
99 #[stable(feature = "rust1", since = "1.0.0")]
100 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
101 #[must_use = "this returns the result of the operation, \
102 without modifying the original"]
104 pub const fn count_zeros(self) -> u32 {
108 /// Returns the number of leading zeros in the binary representation of `self`.
115 #[doc = concat!("let n = -1", stringify!($SelfT), ";")]
117 /// assert_eq!(n.leading_zeros(), 0);
119 #[stable(feature = "rust1", since = "1.0.0")]
120 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
121 #[must_use = "this returns the result of the operation, \
122 without modifying the original"]
124 pub const fn leading_zeros(self) -> u32 {
125 (self as $UnsignedT).leading_zeros()
128 /// Returns the number of trailing zeros in the binary representation of `self`.
135 #[doc = concat!("let n = -4", stringify!($SelfT), ";")]
137 /// assert_eq!(n.trailing_zeros(), 2);
139 #[stable(feature = "rust1", since = "1.0.0")]
140 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
141 #[must_use = "this returns the result of the operation, \
142 without modifying the original"]
144 pub const fn trailing_zeros(self) -> u32 {
145 (self as $UnsignedT).trailing_zeros()
148 /// Returns the number of leading ones in the binary representation of `self`.
155 #[doc = concat!("let n = -1", stringify!($SelfT), ";")]
157 #[doc = concat!("assert_eq!(n.leading_ones(), ", stringify!($BITS), ");")]
159 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
160 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
161 #[must_use = "this returns the result of the operation, \
162 without modifying the original"]
164 pub const fn leading_ones(self) -> u32 {
165 (self as $UnsignedT).leading_ones()
168 /// Returns the number of trailing ones in the binary representation of `self`.
175 #[doc = concat!("let n = 3", stringify!($SelfT), ";")]
177 /// assert_eq!(n.trailing_ones(), 2);
179 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
180 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
181 #[must_use = "this returns the result of the operation, \
182 without modifying the original"]
184 pub const fn trailing_ones(self) -> u32 {
185 (self as $UnsignedT).trailing_ones()
188 /// Shifts the bits to the left by a specified amount, `n`,
189 /// wrapping the truncated bits to the end of the resulting integer.
191 /// Please note this isn't the same operation as the `<<` shifting operator!
198 #[doc = concat!("let n = ", $rot_op, stringify!($SelfT), ";")]
199 #[doc = concat!("let m = ", $rot_result, ";")]
201 #[doc = concat!("assert_eq!(n.rotate_left(", $rot, "), m);")]
203 #[stable(feature = "rust1", since = "1.0.0")]
204 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
205 #[must_use = "this returns the result of the operation, \
206 without modifying the original"]
208 pub const fn rotate_left(self, n: u32) -> Self {
209 (self as $UnsignedT).rotate_left(n) as Self
212 /// Shifts the bits to the right by a specified amount, `n`,
213 /// wrapping the truncated bits to the beginning of the resulting
216 /// Please note this isn't the same operation as the `>>` shifting operator!
223 #[doc = concat!("let n = ", $rot_result, stringify!($SelfT), ";")]
224 #[doc = concat!("let m = ", $rot_op, ";")]
226 #[doc = concat!("assert_eq!(n.rotate_right(", $rot, "), m);")]
228 #[stable(feature = "rust1", since = "1.0.0")]
229 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
230 #[must_use = "this returns the result of the operation, \
231 without modifying the original"]
233 pub const fn rotate_right(self, n: u32) -> Self {
234 (self as $UnsignedT).rotate_right(n) as Self
237 /// Reverses the byte order of the integer.
244 #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
246 /// let m = n.swap_bytes();
248 #[doc = concat!("assert_eq!(m, ", $swapped, ");")]
250 #[stable(feature = "rust1", since = "1.0.0")]
251 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
252 #[must_use = "this returns the result of the operation, \
253 without modifying the original"]
255 pub const fn swap_bytes(self) -> Self {
256 (self as $UnsignedT).swap_bytes() as Self
259 /// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
260 /// second least-significant bit becomes second most-significant bit, etc.
267 #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
268 /// let m = n.reverse_bits();
270 #[doc = concat!("assert_eq!(m, ", $reversed, ");")]
271 #[doc = concat!("assert_eq!(0, 0", stringify!($SelfT), ".reverse_bits());")]
273 #[stable(feature = "reverse_bits", since = "1.37.0")]
274 #[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
275 #[must_use = "this returns the result of the operation, \
276 without modifying the original"]
278 pub const fn reverse_bits(self) -> Self {
279 (self as $UnsignedT).reverse_bits() as Self
282 /// Converts an integer from big endian to the target's endianness.
284 /// On big endian this is a no-op. On little endian the bytes are swapped.
291 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
293 /// if cfg!(target_endian = "big") {
294 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_be(n), n)")]
296 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())")]
299 #[stable(feature = "rust1", since = "1.0.0")]
300 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
303 pub const fn from_be(x: Self) -> Self {
304 #[cfg(target_endian = "big")]
308 #[cfg(not(target_endian = "big"))]
314 /// Converts an integer from little endian to the target's endianness.
316 /// On little endian this is a no-op. On big endian the bytes are swapped.
323 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
325 /// if cfg!(target_endian = "little") {
326 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_le(n), n)")]
328 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())")]
331 #[stable(feature = "rust1", since = "1.0.0")]
332 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
335 pub const fn from_le(x: Self) -> Self {
336 #[cfg(target_endian = "little")]
340 #[cfg(not(target_endian = "little"))]
346 /// Converts `self` to big endian from the target's endianness.
348 /// On big endian this is a no-op. On little endian the bytes are swapped.
355 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
357 /// if cfg!(target_endian = "big") {
358 /// assert_eq!(n.to_be(), n)
360 /// assert_eq!(n.to_be(), n.swap_bytes())
363 #[stable(feature = "rust1", since = "1.0.0")]
364 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
365 #[must_use = "this returns the result of the operation, \
366 without modifying the original"]
368 pub const fn to_be(self) -> Self { // or not to be?
369 #[cfg(target_endian = "big")]
373 #[cfg(not(target_endian = "big"))]
379 /// Converts `self` to little endian from the target's endianness.
381 /// On little endian this is a no-op. On big endian the bytes are swapped.
388 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
390 /// if cfg!(target_endian = "little") {
391 /// assert_eq!(n.to_le(), n)
393 /// assert_eq!(n.to_le(), n.swap_bytes())
396 #[stable(feature = "rust1", since = "1.0.0")]
397 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
398 #[must_use = "this returns the result of the operation, \
399 without modifying the original"]
401 pub const fn to_le(self) -> Self {
402 #[cfg(target_endian = "little")]
406 #[cfg(not(target_endian = "little"))]
412 /// Checked integer addition. Computes `self + rhs`, returning `None`
413 /// if overflow occurred.
420 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(1), Some(", stringify!($SelfT), "::MAX - 1));")]
421 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);")]
423 #[stable(feature = "rust1", since = "1.0.0")]
424 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
425 #[must_use = "this returns the result of the operation, \
426 without modifying the original"]
428 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
429 let (a, b) = self.overflowing_add(rhs);
430 if unlikely!(b) {None} else {Some(a)}
433 /// Unchecked integer addition. Computes `self + rhs`, assuming overflow
438 /// This results in undefined behavior when
439 #[doc = concat!("`self + rhs > ", stringify!($SelfT), "::MAX` or `self + rhs < ", stringify!($SelfT), "::MIN`,")]
440 /// i.e. when [`checked_add`] would return `None`.
442 #[doc = concat!("[`checked_add`]: ", stringify!($SelfT), "::checked_add")]
444 feature = "unchecked_math",
445 reason = "niche optimization path",
448 #[must_use = "this returns the result of the operation, \
449 without modifying the original"]
450 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
452 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
453 pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
454 // SAFETY: the caller must uphold the safety contract for
456 unsafe { intrinsics::unchecked_add(self, rhs) }
459 /// Checked addition with an unsigned integer. Computes `self + rhs`,
460 /// returning `None` if overflow occurred.
467 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_add_unsigned(2), Some(3));")]
468 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add_unsigned(3), None);")]
470 #[stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
471 #[rustc_const_stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
472 #[must_use = "this returns the result of the operation, \
473 without modifying the original"]
475 pub const fn checked_add_unsigned(self, rhs: $UnsignedT) -> Option<Self> {
476 let (a, b) = self.overflowing_add_unsigned(rhs);
477 if unlikely!(b) {None} else {Some(a)}
480 /// Checked integer subtraction. Computes `self - rhs`, returning `None` if
481 /// overflow occurred.
488 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 2).checked_sub(1), Some(", stringify!($SelfT), "::MIN + 1));")]
489 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 2).checked_sub(3), None);")]
491 #[stable(feature = "rust1", since = "1.0.0")]
492 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
493 #[must_use = "this returns the result of the operation, \
494 without modifying the original"]
496 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
497 let (a, b) = self.overflowing_sub(rhs);
498 if unlikely!(b) {None} else {Some(a)}
501 /// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
506 /// This results in undefined behavior when
507 #[doc = concat!("`self - rhs > ", stringify!($SelfT), "::MAX` or `self - rhs < ", stringify!($SelfT), "::MIN`,")]
508 /// i.e. when [`checked_sub`] would return `None`.
510 #[doc = concat!("[`checked_sub`]: ", stringify!($SelfT), "::checked_sub")]
512 feature = "unchecked_math",
513 reason = "niche optimization path",
516 #[must_use = "this returns the result of the operation, \
517 without modifying the original"]
518 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
520 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
521 pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
522 // SAFETY: the caller must uphold the safety contract for
524 unsafe { intrinsics::unchecked_sub(self, rhs) }
527 /// Checked subtraction with an unsigned integer. Computes `self - rhs`,
528 /// returning `None` if overflow occurred.
535 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_sub_unsigned(2), Some(-1));")]
536 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 2).checked_sub_unsigned(3), None);")]
538 #[stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
539 #[rustc_const_stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
540 #[must_use = "this returns the result of the operation, \
541 without modifying the original"]
543 pub const fn checked_sub_unsigned(self, rhs: $UnsignedT) -> Option<Self> {
544 let (a, b) = self.overflowing_sub_unsigned(rhs);
545 if unlikely!(b) {None} else {Some(a)}
548 /// Checked integer multiplication. Computes `self * rhs`, returning `None` if
549 /// overflow occurred.
556 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(1), Some(", stringify!($SelfT), "::MAX));")]
557 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);")]
559 #[stable(feature = "rust1", since = "1.0.0")]
560 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
561 #[must_use = "this returns the result of the operation, \
562 without modifying the original"]
564 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
565 let (a, b) = self.overflowing_mul(rhs);
566 if unlikely!(b) {None} else {Some(a)}
569 /// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
574 /// This results in undefined behavior when
575 #[doc = concat!("`self * rhs > ", stringify!($SelfT), "::MAX` or `self * rhs < ", stringify!($SelfT), "::MIN`,")]
576 /// i.e. when [`checked_mul`] would return `None`.
578 #[doc = concat!("[`checked_mul`]: ", stringify!($SelfT), "::checked_mul")]
580 feature = "unchecked_math",
581 reason = "niche optimization path",
584 #[must_use = "this returns the result of the operation, \
585 without modifying the original"]
586 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
588 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
589 pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
590 // SAFETY: the caller must uphold the safety contract for
592 unsafe { intrinsics::unchecked_mul(self, rhs) }
595 /// Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
596 /// or the division results in overflow.
603 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 1).checked_div(-1), Some(", stringify!($Max), "));")]
604 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_div(-1), None);")]
605 #[doc = concat!("assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);")]
607 #[stable(feature = "rust1", since = "1.0.0")]
608 #[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
609 #[must_use = "this returns the result of the operation, \
610 without modifying the original"]
612 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
613 if unlikely!(rhs == 0 || ((self == Self::MIN) && (rhs == -1))) {
616 // SAFETY: div by zero and by INT_MIN have been checked above
617 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
621 /// Checked Euclidean division. Computes `self.div_euclid(rhs)`,
622 /// returning `None` if `rhs == 0` or the division results in overflow.
629 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 1).checked_div_euclid(-1), Some(", stringify!($Max), "));")]
630 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_div_euclid(-1), None);")]
631 #[doc = concat!("assert_eq!((1", stringify!($SelfT), ").checked_div_euclid(0), None);")]
633 #[stable(feature = "euclidean_division", since = "1.38.0")]
634 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
635 #[must_use = "this returns the result of the operation, \
636 without modifying the original"]
638 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
639 // Using `&` helps LLVM see that it is the same check made in division.
640 if unlikely!(rhs == 0 || ((self == Self::MIN) & (rhs == -1))) {
643 Some(self.div_euclid(rhs))
647 /// Checked integer remainder. Computes `self % rhs`, returning `None` if
648 /// `rhs == 0` or the division results in overflow.
655 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));")]
656 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);")]
657 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);")]
659 #[stable(feature = "wrapping", since = "1.7.0")]
660 #[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
661 #[must_use = "this returns the result of the operation, \
662 without modifying the original"]
664 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
665 if unlikely!(rhs == 0 || ((self == Self::MIN) && (rhs == -1))) {
668 // SAFETY: div by zero and by INT_MIN have been checked above
669 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
673 /// Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`
674 /// if `rhs == 0` or the division results in overflow.
681 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));")]
682 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);")]
683 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_rem_euclid(-1), None);")]
685 #[stable(feature = "euclidean_division", since = "1.38.0")]
686 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
687 #[must_use = "this returns the result of the operation, \
688 without modifying the original"]
690 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
691 // Using `&` helps LLVM see that it is the same check made in division.
692 if unlikely!(rhs == 0 || ((self == Self::MIN) & (rhs == -1))) {
695 Some(self.rem_euclid(rhs))
699 /// 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 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
760 pub const unsafe fn unchecked_shl(self, rhs: Self) -> Self {
761 // SAFETY: the caller must uphold the safety contract for
763 unsafe { intrinsics::unchecked_shl(self, rhs) }
766 /// Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
767 /// larger than or equal to the number of bits in `self`.
774 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));")]
775 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);")]
777 #[stable(feature = "wrapping", since = "1.7.0")]
778 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
779 #[must_use = "this returns the result of the operation, \
780 without modifying the original"]
782 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
783 let (a, b) = self.overflowing_shr(rhs);
784 if unlikely!(b) {None} else {Some(a)}
787 /// Unchecked shift right. Computes `self >> rhs`, assuming that
788 /// `rhs` is less than the number of bits in `self`.
792 /// This results in undefined behavior if `rhs` is larger than
793 /// or equal to the number of bits in `self`,
794 /// i.e. when [`checked_shr`] would return `None`.
796 #[doc = concat!("[`checked_shr`]: ", stringify!($SelfT), "::checked_shr")]
798 feature = "unchecked_math",
799 reason = "niche optimization path",
802 #[must_use = "this returns the result of the operation, \
803 without modifying the original"]
804 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
806 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
807 pub const unsafe fn unchecked_shr(self, rhs: Self) -> Self {
808 // SAFETY: the caller must uphold the safety contract for
810 unsafe { intrinsics::unchecked_shr(self, rhs) }
813 /// Checked absolute value. Computes `self.abs()`, returning `None` if
821 #[doc = concat!("assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));")]
822 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);")]
824 #[stable(feature = "no_panic_abs", since = "1.13.0")]
825 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
826 #[must_use = "this returns the result of the operation, \
827 without modifying the original"]
829 pub const fn checked_abs(self) -> Option<Self> {
830 if self.is_negative() {
837 /// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
838 /// overflow occurred.
845 #[doc = concat!("assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));")]
846 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);")]
849 #[stable(feature = "no_panic_pow", since = "1.34.0")]
850 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
851 #[must_use = "this returns the result of the operation, \
852 without modifying the original"]
854 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
859 let mut acc: Self = 1;
863 acc = try_opt!(acc.checked_mul(base));
866 base = try_opt!(base.checked_mul(base));
868 // since exp!=0, finally the exp must be 1.
869 // Deal with the final bit of the exponent separately, since
870 // squaring the base afterwards is not necessary and may cause a
871 // needless overflow.
872 Some(try_opt!(acc.checked_mul(base)))
875 /// Saturating integer addition. Computes `self + rhs`, saturating at the numeric
876 /// bounds instead of overflowing.
883 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);")]
884 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(100), ", stringify!($SelfT), "::MAX);")]
885 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_add(-1), ", stringify!($SelfT), "::MIN);")]
888 #[stable(feature = "rust1", since = "1.0.0")]
889 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
890 #[must_use = "this returns the result of the operation, \
891 without modifying the original"]
893 pub const fn saturating_add(self, rhs: Self) -> Self {
894 intrinsics::saturating_add(self, rhs)
897 /// Saturating addition with an unsigned integer. Computes `self + rhs`,
898 /// saturating at the numeric bounds instead of overflowing.
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 #[stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
909 #[rustc_const_stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
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 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_sub_unsigned(127), -27);")]
952 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_sub_unsigned(100), ", stringify!($SelfT), "::MIN);")]
954 #[stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
955 #[rustc_const_stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
956 #[must_use = "this returns the result of the operation, \
957 without modifying the original"]
959 pub const fn saturating_sub_unsigned(self, rhs: $UnsignedT) -> Self {
960 // Overflow can only happen at the lower bound
961 // We cannot use `unwrap_or` here because it is not `const`
962 match self.checked_sub_unsigned(rhs) {
968 /// Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
969 /// instead of overflowing.
976 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_neg(), -100);")]
977 #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").saturating_neg(), 100);")]
978 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_neg(), ", stringify!($SelfT), "::MAX);")]
979 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_neg(), ", stringify!($SelfT), "::MIN + 1);")]
982 #[stable(feature = "saturating_neg", since = "1.45.0")]
983 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
984 #[must_use = "this returns the result of the operation, \
985 without modifying the original"]
987 pub const fn saturating_neg(self) -> Self {
988 intrinsics::saturating_sub(0, self)
991 /// Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
992 /// MIN` instead of overflowing.
999 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_abs(), 100);")]
1000 #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").saturating_abs(), 100);")]
1001 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_abs(), ", stringify!($SelfT), "::MAX);")]
1002 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 1).saturating_abs(), ", stringify!($SelfT), "::MAX);")]
1005 #[stable(feature = "saturating_neg", since = "1.45.0")]
1006 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1007 #[must_use = "this returns the result of the operation, \
1008 without modifying the original"]
1010 pub const fn saturating_abs(self) -> Self {
1011 if self.is_negative() {
1012 self.saturating_neg()
1018 /// Saturating integer multiplication. Computes `self * rhs`, saturating at the
1019 /// numeric bounds instead of overflowing.
1026 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);")]
1027 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);")]
1028 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);")]
1030 #[stable(feature = "wrapping", since = "1.7.0")]
1031 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1032 #[must_use = "this returns the result of the operation, \
1033 without modifying the original"]
1035 pub const fn saturating_mul(self, rhs: Self) -> Self {
1036 match self.checked_mul(rhs) {
1038 None => if (self < 0) == (rhs < 0) {
1046 /// Saturating integer division. Computes `self / rhs`, saturating at the
1047 /// numeric bounds instead of overflowing.
1054 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".saturating_div(2), 2);")]
1055 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_div(-1), ", stringify!($SelfT), "::MIN + 1);")]
1056 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_div(-1), ", stringify!($SelfT), "::MAX);")]
1061 #[doc = concat!("let _ = 1", stringify!($SelfT), ".saturating_div(0);")]
1064 #[stable(feature = "saturating_div", since = "1.58.0")]
1065 #[rustc_const_stable(feature = "saturating_div", since = "1.58.0")]
1066 #[must_use = "this returns the result of the operation, \
1067 without modifying the original"]
1069 pub const fn saturating_div(self, rhs: Self) -> Self {
1070 match self.overflowing_div(rhs) {
1071 (result, false) => result,
1072 (_result, true) => Self::MAX, // MIN / -1 is the only possible saturating overflow
1076 /// Saturating integer exponentiation. Computes `self.pow(exp)`,
1077 /// saturating at the numeric bounds instead of overflowing.
1084 #[doc = concat!("assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);")]
1085 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);")]
1086 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);")]
1088 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1089 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1090 #[must_use = "this returns the result of the operation, \
1091 without modifying the original"]
1093 pub const fn saturating_pow(self, exp: u32) -> Self {
1094 match self.checked_pow(exp) {
1096 None if self < 0 && exp % 2 == 1 => Self::MIN,
1101 /// Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
1102 /// boundary of the type.
1109 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);")]
1110 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_add(2), ", stringify!($SelfT), "::MIN + 1);")]
1112 #[stable(feature = "rust1", since = "1.0.0")]
1113 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1114 #[must_use = "this returns the result of the operation, \
1115 without modifying the original"]
1117 pub const fn wrapping_add(self, rhs: Self) -> Self {
1118 intrinsics::wrapping_add(self, rhs)
1121 /// Wrapping (modular) addition with an unsigned integer. Computes
1122 /// `self + rhs`, wrapping around at the boundary of the type.
1129 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_add_unsigned(27), 127);")]
1130 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_add_unsigned(2), ", stringify!($SelfT), "::MIN + 1);")]
1132 #[stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
1133 #[rustc_const_stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
1134 #[must_use = "this returns the result of the operation, \
1135 without modifying the original"]
1137 pub const fn wrapping_add_unsigned(self, rhs: $UnsignedT) -> Self {
1138 self.wrapping_add(rhs as Self)
1141 /// Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1142 /// boundary of the type.
1149 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);")]
1150 #[doc = concat!("assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::MAX), ", stringify!($SelfT), "::MAX);")]
1152 #[stable(feature = "rust1", since = "1.0.0")]
1153 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1154 #[must_use = "this returns the result of the operation, \
1155 without modifying the original"]
1157 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1158 intrinsics::wrapping_sub(self, rhs)
1161 /// Wrapping (modular) subtraction with an unsigned integer. Computes
1162 /// `self - rhs`, wrapping around at the boundary of the type.
1169 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".wrapping_sub_unsigned(127), -127);")]
1170 #[doc = concat!("assert_eq!((-2", stringify!($SelfT), ").wrapping_sub_unsigned(", stringify!($UnsignedT), "::MAX), -1);")]
1172 #[stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
1173 #[rustc_const_stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
1174 #[must_use = "this returns the result of the operation, \
1175 without modifying the original"]
1177 pub const fn wrapping_sub_unsigned(self, rhs: $UnsignedT) -> Self {
1178 self.wrapping_sub(rhs as Self)
1181 /// Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1182 /// the boundary of the type.
1189 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);")]
1190 /// assert_eq!(11i8.wrapping_mul(12), -124);
1192 #[stable(feature = "rust1", since = "1.0.0")]
1193 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1194 #[must_use = "this returns the result of the operation, \
1195 without modifying the original"]
1197 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1198 intrinsics::wrapping_mul(self, rhs)
1201 /// Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1202 /// boundary of the type.
1204 /// The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1205 /// `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1206 /// that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1210 /// This function will panic if `rhs` is 0.
1217 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);")]
1218 /// assert_eq!((-128i8).wrapping_div(-1), -128);
1220 #[stable(feature = "num_wrapping", since = "1.2.0")]
1221 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1222 #[must_use = "this returns the result of the operation, \
1223 without modifying the original"]
1225 pub const fn wrapping_div(self, rhs: Self) -> Self {
1226 self.overflowing_div(rhs).0
1229 /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
1230 /// wrapping around at the boundary of the type.
1232 /// Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1233 /// for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1234 /// type. In this case, this method returns `MIN` itself.
1238 /// This function will panic if `rhs` is 0.
1245 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);")]
1246 /// assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
1248 #[stable(feature = "euclidean_division", since = "1.38.0")]
1249 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1250 #[must_use = "this returns the result of the operation, \
1251 without modifying the original"]
1253 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
1254 self.overflowing_div_euclid(rhs).0
1257 /// Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1258 /// boundary of the type.
1260 /// Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1261 /// invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1262 /// this function returns `0`.
1266 /// This function will panic if `rhs` is 0.
1273 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);")]
1274 /// assert_eq!((-128i8).wrapping_rem(-1), 0);
1276 #[stable(feature = "num_wrapping", since = "1.2.0")]
1277 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1278 #[must_use = "this returns the result of the operation, \
1279 without modifying the original"]
1281 pub const fn wrapping_rem(self, rhs: Self) -> Self {
1282 self.overflowing_rem(rhs).0
1285 /// Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
1286 /// at the boundary of the type.
1288 /// Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1289 /// for the type). In this case, this method returns 0.
1293 /// This function will panic if `rhs` is 0.
1300 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);")]
1301 /// assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
1303 #[stable(feature = "euclidean_division", since = "1.38.0")]
1304 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1305 #[must_use = "this returns the result of the operation, \
1306 without modifying the original"]
1308 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1309 self.overflowing_rem_euclid(rhs).0
1312 /// Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1315 /// The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1316 /// is the negative minimal value for the type); this is a positive value that is too large to represent
1317 /// in the type. In such a case, this function returns `MIN` itself.
1324 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);")]
1325 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.wrapping_neg(), ", stringify!($SelfT), "::MIN);")]
1327 #[stable(feature = "num_wrapping", since = "1.2.0")]
1328 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1329 #[must_use = "this returns the result of the operation, \
1330 without modifying the original"]
1332 pub const fn wrapping_neg(self) -> Self {
1333 (0 as $SelfT).wrapping_sub(self)
1336 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1337 /// any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1339 /// Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1340 /// the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1341 /// The primitive integer types all implement a [`rotate_left`](Self::rotate_left) function,
1342 /// which may be what you want instead.
1349 #[doc = concat!("assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);")]
1350 #[doc = concat!("assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);")]
1352 #[stable(feature = "num_wrapping", since = "1.2.0")]
1353 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1354 #[must_use = "this returns the result of the operation, \
1355 without modifying the original"]
1357 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1358 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1361 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1365 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1366 /// removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1368 /// Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1369 /// to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1370 /// end. The primitive integer types all implement a [`rotate_right`](Self::rotate_right) function,
1371 /// which may be what you want instead.
1378 #[doc = concat!("assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);")]
1379 /// assert_eq!((-128i16).wrapping_shr(64), -128);
1381 #[stable(feature = "num_wrapping", since = "1.2.0")]
1382 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1383 #[must_use = "this returns the result of the operation, \
1384 without modifying the original"]
1386 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1387 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1390 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1394 /// Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1395 /// the boundary of the type.
1397 /// The only case where such wrapping can occur is when one takes the absolute value of the negative
1398 /// minimal value for the type; this is a positive value that is too large to represent in the type. In
1399 /// such a case, this function returns `MIN` itself.
1406 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);")]
1407 #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);")]
1408 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.wrapping_abs(), ", stringify!($SelfT), "::MIN);")]
1409 /// assert_eq!((-128i8).wrapping_abs() as u8, 128);
1411 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1412 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1413 #[must_use = "this returns the result of the operation, \
1414 without modifying the original"]
1415 #[allow(unused_attributes)]
1417 pub const fn wrapping_abs(self) -> Self {
1418 if self.is_negative() {
1425 /// Computes the absolute value of `self` without any wrapping
1434 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".unsigned_abs(), 100", stringify!($UnsignedT), ");")]
1435 #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").unsigned_abs(), 100", stringify!($UnsignedT), ");")]
1436 /// assert_eq!((-128i8).unsigned_abs(), 128u8);
1438 #[stable(feature = "unsigned_abs", since = "1.51.0")]
1439 #[rustc_const_stable(feature = "unsigned_abs", since = "1.51.0")]
1440 #[must_use = "this returns the result of the operation, \
1441 without modifying the original"]
1443 pub const fn unsigned_abs(self) -> $UnsignedT {
1444 self.wrapping_abs() as $UnsignedT
1447 /// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1448 /// wrapping around at the boundary of the type.
1455 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);")]
1456 /// assert_eq!(3i8.wrapping_pow(5), -13);
1457 /// assert_eq!(3i8.wrapping_pow(6), -39);
1459 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1460 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1461 #[must_use = "this returns the result of the operation, \
1462 without modifying the original"]
1464 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
1468 let mut base = self;
1469 let mut acc: Self = 1;
1473 acc = acc.wrapping_mul(base);
1476 base = base.wrapping_mul(base);
1479 // since exp!=0, finally the exp must be 1.
1480 // Deal with the final bit of the exponent separately, since
1481 // squaring the base afterwards is not necessary and may cause a
1482 // needless overflow.
1483 acc.wrapping_mul(base)
1486 /// Calculates `self` + `rhs`
1488 /// Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1489 /// occur. If an overflow would have occurred then the wrapped value is returned.
1496 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));")]
1497 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT), "::MIN, true));")]
1499 #[stable(feature = "wrapping", since = "1.7.0")]
1500 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1501 #[must_use = "this returns the result of the operation, \
1502 without modifying the original"]
1504 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1505 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1509 /// Calculates `self + rhs + carry` without the ability to overflow.
1511 /// Performs "signed ternary addition" which takes in an extra bit to add, and may return an
1512 /// additional bit of overflow. This signed function is used only on the highest-ordered data,
1513 /// for which the signed overflow result indicates whether the big integer overflowed or not.
1520 /// #![feature(bigint_helper_methods)]
1521 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".carrying_add(2, false), (7, false));")]
1522 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".carrying_add(2, true), (8, false));")]
1523 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.carrying_add(1, false), (", stringify!($SelfT), "::MIN, true));")]
1524 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.carrying_add(0, true), (", stringify!($SelfT), "::MIN, true));")]
1525 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.carrying_add(1, true), (", stringify!($SelfT), "::MIN + 1, true));")]
1526 #[doc = concat!("assert_eq!(",
1527 stringify!($SelfT), "::MAX.carrying_add(", stringify!($SelfT), "::MAX, true), ",
1530 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.carrying_add(-1, true), (", stringify!($SelfT), "::MIN, false));")]
1531 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".carrying_add(", stringify!($SelfT), "::MAX, true), (", stringify!($SelfT), "::MIN, true));")]
1534 /// If `carry` is false, this method is equivalent to [`overflowing_add`](Self::overflowing_add):
1537 /// #![feature(bigint_helper_methods)]
1538 #[doc = concat!("assert_eq!(5_", stringify!($SelfT), ".carrying_add(2, false), 5_", stringify!($SelfT), ".overflowing_add(2));")]
1539 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.carrying_add(1, false), ", stringify!($SelfT), "::MAX.overflowing_add(1));")]
1541 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
1542 #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")]
1543 #[must_use = "this returns the result of the operation, \
1544 without modifying the original"]
1546 pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
1547 // note: longer-term this should be done via an intrinsic.
1548 // note: no intermediate overflow is required (https://github.com/rust-lang/rust/issues/85532#issuecomment-1032214946).
1549 let (a, b) = self.overflowing_add(rhs);
1550 let (c, d) = a.overflowing_add(carry as $SelfT);
1554 /// Calculates `self` + `rhs` with an unsigned `rhs`
1556 /// Returns a tuple of the addition along with a boolean indicating
1557 /// whether an arithmetic overflow would occur. If an overflow would
1558 /// have occurred then the wrapped value is returned.
1565 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_unsigned(2), (3, false));")]
1566 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN).overflowing_add_unsigned(", stringify!($UnsignedT), "::MAX), (", stringify!($SelfT), "::MAX, false));")]
1567 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).overflowing_add_unsigned(3), (", stringify!($SelfT), "::MIN, true));")]
1569 #[stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
1570 #[rustc_const_stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
1571 #[must_use = "this returns the result of the operation, \
1572 without modifying the original"]
1574 pub const fn overflowing_add_unsigned(self, rhs: $UnsignedT) -> (Self, bool) {
1575 let rhs = rhs as Self;
1576 let (res, overflowed) = self.overflowing_add(rhs);
1577 (res, overflowed ^ (rhs < 0))
1580 /// Calculates `self` - `rhs`
1582 /// Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1583 /// would occur. If an overflow would have occurred then the wrapped value is returned.
1590 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));")]
1591 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")]
1593 #[stable(feature = "wrapping", since = "1.7.0")]
1594 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1595 #[must_use = "this returns the result of the operation, \
1596 without modifying the original"]
1598 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1599 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1603 /// Calculates `self - rhs - borrow` without the ability to overflow.
1605 /// Performs "signed ternary subtraction" which takes in an extra bit to subtract, and may return an
1606 /// additional bit of overflow. This signed function is used only on the highest-ordered data,
1607 /// for which the signed overflow result indicates whether the big integer overflowed or not.
1614 /// #![feature(bigint_helper_methods)]
1615 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".borrowing_sub(2, false), (3, false));")]
1616 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".borrowing_sub(2, true), (2, false));")]
1617 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".borrowing_sub(1, false), (-1, false));")]
1618 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".borrowing_sub(1, true), (-2, false));")]
1619 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.borrowing_sub(1, true), (", stringify!($SelfT), "::MAX - 1, true));")]
1620 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.borrowing_sub(-1, false), (", stringify!($SelfT), "::MIN, true));")]
1621 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.borrowing_sub(-1, true), (", stringify!($SelfT), "::MAX, false));")]
1623 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
1624 #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")]
1625 #[must_use = "this returns the result of the operation, \
1626 without modifying the original"]
1628 pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
1629 // note: longer-term this should be done via an intrinsic.
1630 // note: no intermediate overflow is required (https://github.com/rust-lang/rust/issues/85532#issuecomment-1032214946).
1631 let (a, b) = self.overflowing_sub(rhs);
1632 let (c, d) = a.overflowing_sub(borrow as $SelfT);
1636 /// Calculates `self` - `rhs` with an unsigned `rhs`
1638 /// Returns a tuple of the subtraction along with a boolean indicating
1639 /// whether an arithmetic overflow would occur. If an overflow would
1640 /// have occurred then the wrapped value is returned.
1647 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_sub_unsigned(2), (-1, false));")]
1648 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX).overflowing_sub_unsigned(", stringify!($UnsignedT), "::MAX), (", stringify!($SelfT), "::MIN, false));")]
1649 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 2).overflowing_sub_unsigned(3), (", stringify!($SelfT), "::MAX, true));")]
1651 #[stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
1652 #[rustc_const_stable(feature = "mixed_integer_ops", since = "CURRENT_RUSTC_VERSION")]
1653 #[must_use = "this returns the result of the operation, \
1654 without modifying the original"]
1656 pub const fn overflowing_sub_unsigned(self, rhs: $UnsignedT) -> (Self, bool) {
1657 let rhs = rhs as Self;
1658 let (res, overflowed) = self.overflowing_sub(rhs);
1659 (res, overflowed ^ (rhs < 0))
1662 /// Calculates the multiplication of `self` and `rhs`.
1664 /// Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1665 /// would occur. If an overflow would have occurred then the wrapped value is returned.
1672 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));")]
1673 /// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
1675 #[stable(feature = "wrapping", since = "1.7.0")]
1676 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1677 #[must_use = "this returns the result of the operation, \
1678 without modifying the original"]
1680 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1681 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1685 /// Calculates the divisor when `self` is divided by `rhs`.
1687 /// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1688 /// occur. If an overflow would occur then self is returned.
1692 /// This function will panic if `rhs` is 0.
1699 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));")]
1700 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT), "::MIN, true));")]
1703 #[stable(feature = "wrapping", since = "1.7.0")]
1704 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1705 #[must_use = "this returns the result of the operation, \
1706 without modifying the original"]
1707 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1708 // Using `&` helps LLVM see that it is the same check made in division.
1709 if unlikely!((self == Self::MIN) & (rhs == -1)) {
1716 /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1718 /// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1719 /// occur. If an overflow would occur then `self` is returned.
1723 /// This function will panic if `rhs` is 0.
1730 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));")]
1731 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euclid(-1), (", stringify!($SelfT), "::MIN, true));")]
1734 #[stable(feature = "euclidean_division", since = "1.38.0")]
1735 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1736 #[must_use = "this returns the result of the operation, \
1737 without modifying the original"]
1738 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1739 // Using `&` helps LLVM see that it is the same check made in division.
1740 if unlikely!((self == Self::MIN) & (rhs == -1)) {
1743 (self.div_euclid(rhs), false)
1747 /// Calculates the remainder when `self` is divided by `rhs`.
1749 /// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1750 /// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1754 /// This function will panic if `rhs` is 0.
1761 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));")]
1762 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));")]
1765 #[stable(feature = "wrapping", since = "1.7.0")]
1766 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1767 #[must_use = "this returns the result of the operation, \
1768 without modifying the original"]
1769 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1770 if unlikely!(rhs == -1) {
1771 (0, self == Self::MIN)
1778 /// Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
1780 /// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1781 /// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1785 /// This function will panic if `rhs` is 0.
1792 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));")]
1793 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem_euclid(-1), (0, true));")]
1795 #[stable(feature = "euclidean_division", since = "1.38.0")]
1796 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1797 #[must_use = "this returns the result of the operation, \
1798 without modifying the original"]
1800 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1801 if unlikely!(rhs == -1) {
1802 (0, self == Self::MIN)
1804 (self.rem_euclid(rhs), false)
1809 /// Negates self, overflowing if this is equal to the minimum value.
1811 /// Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1812 /// happened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the
1813 /// minimum value will be returned again and `true` will be returned for an overflow happening.
1820 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));")]
1821 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT), "::MIN, true));")]
1824 #[stable(feature = "wrapping", since = "1.7.0")]
1825 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1826 #[must_use = "this returns the result of the operation, \
1827 without modifying the original"]
1828 #[allow(unused_attributes)]
1829 pub const fn overflowing_neg(self) -> (Self, bool) {
1830 if unlikely!(self == Self::MIN) {
1837 /// Shifts self left by `rhs` bits.
1839 /// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1840 /// value was larger than or equal to the number of bits. If the shift value is too large, then value is
1841 /// masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1848 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));")]
1849 /// assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));
1851 #[stable(feature = "wrapping", since = "1.7.0")]
1852 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1853 #[must_use = "this returns the result of the operation, \
1854 without modifying the original"]
1856 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1857 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1860 /// Shifts self right by `rhs` bits.
1862 /// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1863 /// value was larger than or equal to the number of bits. If the shift value is too large, then value is
1864 /// masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1871 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));")]
1872 /// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
1874 #[stable(feature = "wrapping", since = "1.7.0")]
1875 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1876 #[must_use = "this returns the result of the operation, \
1877 without modifying the original"]
1879 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1880 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1883 /// Computes the absolute value of `self`.
1885 /// Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1886 /// happened. If self is the minimum value
1887 #[doc = concat!("(e.g., ", stringify!($SelfT), "::MIN for values of type ", stringify!($SelfT), "),")]
1888 /// then the minimum value will be returned again and true will be returned
1889 /// for an overflow happening.
1896 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));")]
1897 #[doc = concat!("assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));")]
1898 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN).overflowing_abs(), (", stringify!($SelfT), "::MIN, true));")]
1900 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1901 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1902 #[must_use = "this returns the result of the operation, \
1903 without modifying the original"]
1905 pub const fn overflowing_abs(self) -> (Self, bool) {
1906 (self.wrapping_abs(), self == Self::MIN)
1909 /// Raises self to the power of `exp`, using exponentiation by squaring.
1911 /// Returns a tuple of the exponentiation along with a bool indicating
1912 /// whether an overflow happened.
1919 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));")]
1920 /// assert_eq!(3i8.overflowing_pow(5), (-13, true));
1922 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1923 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1924 #[must_use = "this returns the result of the operation, \
1925 without modifying the original"]
1927 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1931 let mut base = self;
1932 let mut acc: Self = 1;
1933 let mut overflown = false;
1934 // Scratch space for storing results of overflowing_mul.
1939 r = acc.overflowing_mul(base);
1944 r = base.overflowing_mul(base);
1949 // since exp!=0, finally the exp must be 1.
1950 // Deal with the final bit of the exponent separately, since
1951 // squaring the base afterwards is not necessary and may cause a
1952 // needless overflow.
1953 r = acc.overflowing_mul(base);
1958 /// Raises self to the power of `exp`, using exponentiation by squaring.
1965 #[doc = concat!("let x: ", stringify!($SelfT), " = 2; // or any other integer type")]
1967 /// assert_eq!(x.pow(5), 32);
1969 #[stable(feature = "rust1", since = "1.0.0")]
1970 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1971 #[must_use = "this returns the result of the operation, \
1972 without modifying the original"]
1974 #[rustc_inherit_overflow_checks]
1975 pub const fn pow(self, mut exp: u32) -> Self {
1979 let mut base = self;
1990 // since exp!=0, finally the exp must be 1.
1991 // Deal with the final bit of the exponent separately, since
1992 // squaring the base afterwards is not necessary and may cause a
1993 // needless overflow.
1997 /// Calculates the quotient of Euclidean division of `self` by `rhs`.
1999 /// This computes the integer `q` such that `self = q * rhs + r`, with
2000 /// `r = self.rem_euclid(rhs)` and `0 <= r < abs(rhs)`.
2002 /// In other words, the result is `self / rhs` rounded to the integer `q`
2003 /// such that `self >= q * rhs`.
2004 /// If `self > 0`, this is equal to round towards zero (the default in Rust);
2005 /// if `self < 0`, this is equal to round towards +/- infinity.
2009 /// This function will panic if `rhs` is 0 or the division results in overflow.
2016 #[doc = concat!("let a: ", stringify!($SelfT), " = 7; // or any other integer type")]
2019 /// assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
2020 /// assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
2021 /// assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
2022 /// assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
2024 #[stable(feature = "euclidean_division", since = "1.38.0")]
2025 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
2026 #[must_use = "this returns the result of the operation, \
2027 without modifying the original"]
2029 #[rustc_inherit_overflow_checks]
2030 pub const fn div_euclid(self, rhs: Self) -> Self {
2033 return if rhs > 0 { q - 1 } else { q + 1 }
2039 /// Calculates the least nonnegative remainder of `self (mod rhs)`.
2041 /// This is done as if by the Euclidean division algorithm -- given
2042 /// `r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) + r`, and
2043 /// `0 <= r < abs(rhs)`.
2047 /// This function will panic if `rhs` is 0 or the division results in overflow.
2054 #[doc = concat!("let a: ", stringify!($SelfT), " = 7; // or any other integer type")]
2057 /// assert_eq!(a.rem_euclid(b), 3);
2058 /// assert_eq!((-a).rem_euclid(b), 1);
2059 /// assert_eq!(a.rem_euclid(-b), 3);
2060 /// assert_eq!((-a).rem_euclid(-b), 1);
2062 #[stable(feature = "euclidean_division", since = "1.38.0")]
2063 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
2064 #[must_use = "this returns the result of the operation, \
2065 without modifying the original"]
2067 #[rustc_inherit_overflow_checks]
2068 pub const fn rem_euclid(self, rhs: Self) -> Self {
2081 /// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
2085 /// This function will panic if `rhs` is zero.
2087 /// ## Overflow behavior
2089 /// On overflow, this function will panic if overflow checks are enabled (default in debug
2090 /// mode) and wrap if overflow checks are disabled (default in release mode).
2097 /// #![feature(int_roundings)]
2098 #[doc = concat!("let a: ", stringify!($SelfT)," = 8;")]
2101 /// assert_eq!(a.div_floor(b), 2);
2102 /// assert_eq!(a.div_floor(-b), -3);
2103 /// assert_eq!((-a).div_floor(b), -3);
2104 /// assert_eq!((-a).div_floor(-b), 2);
2106 #[unstable(feature = "int_roundings", issue = "88581")]
2107 #[must_use = "this returns the result of the operation, \
2108 without modifying the original"]
2110 #[rustc_inherit_overflow_checks]
2111 pub const fn div_floor(self, rhs: Self) -> Self {
2114 if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) {
2121 /// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
2125 /// This function will panic if `rhs` is zero.
2127 /// ## Overflow behavior
2129 /// On overflow, this function will panic if overflow checks are enabled (default in debug
2130 /// mode) and wrap if overflow checks are disabled (default in release mode).
2137 /// #![feature(int_roundings)]
2138 #[doc = concat!("let a: ", stringify!($SelfT)," = 8;")]
2141 /// assert_eq!(a.div_ceil(b), 3);
2142 /// assert_eq!(a.div_ceil(-b), -2);
2143 /// assert_eq!((-a).div_ceil(b), -2);
2144 /// assert_eq!((-a).div_ceil(-b), 3);
2146 #[unstable(feature = "int_roundings", issue = "88581")]
2147 #[must_use = "this returns the result of the operation, \
2148 without modifying the original"]
2150 #[rustc_inherit_overflow_checks]
2151 pub const fn div_ceil(self, rhs: Self) -> Self {
2154 if (r > 0 && rhs > 0) || (r < 0 && rhs < 0) {
2161 /// If `rhs` is positive, calculates the smallest value greater than or
2162 /// equal to `self` that is a multiple of `rhs`. If `rhs` is negative,
2163 /// calculates the largest value less than or equal to `self` that is a
2164 /// multiple of `rhs`.
2168 /// This function will panic if `rhs` is zero.
2170 /// ## Overflow behavior
2172 /// On overflow, this function will panic if overflow checks are enabled (default in debug
2173 /// mode) and wrap if overflow checks are disabled (default in release mode).
2180 /// #![feature(int_roundings)]
2181 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".next_multiple_of(8), 16);")]
2182 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".next_multiple_of(8), 24);")]
2183 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".next_multiple_of(-8), 16);")]
2184 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".next_multiple_of(-8), 16);")]
2185 #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").next_multiple_of(8), -16);")]
2186 #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").next_multiple_of(8), -16);")]
2187 #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").next_multiple_of(-8), -16);")]
2188 #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").next_multiple_of(-8), -24);")]
2190 #[unstable(feature = "int_roundings", issue = "88581")]
2191 #[must_use = "this returns the result of the operation, \
2192 without modifying the original"]
2194 #[rustc_inherit_overflow_checks]
2195 pub const fn next_multiple_of(self, rhs: Self) -> Self {
2196 // This would otherwise fail when calculating `r` when self == T::MIN.
2202 let m = if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) {
2215 /// If `rhs` is positive, calculates the smallest value greater than or
2216 /// equal to `self` that is a multiple of `rhs`. If `rhs` is negative,
2217 /// calculates the largest value less than or equal to `self` that is a
2218 /// multiple of `rhs`. Returns `None` if `rhs` is zero or the operation
2219 /// would result in overflow.
2226 /// #![feature(int_roundings)]
2227 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(16));")]
2228 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(24));")]
2229 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(-8), Some(16));")]
2230 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(-8), Some(16));")]
2231 #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").checked_next_multiple_of(8), Some(-16));")]
2232 #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").checked_next_multiple_of(8), Some(-16));")]
2233 #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").checked_next_multiple_of(-8), Some(-16));")]
2234 #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").checked_next_multiple_of(-8), Some(-24));")]
2235 #[doc = concat!("assert_eq!(1_", stringify!($SelfT), ".checked_next_multiple_of(0), None);")]
2236 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_multiple_of(2), None);")]
2238 #[unstable(feature = "int_roundings", issue = "88581")]
2239 #[must_use = "this returns the result of the operation, \
2240 without modifying the original"]
2242 pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
2243 // This would otherwise fail when calculating `r` when self == T::MIN.
2248 let r = try_opt!(self.checked_rem(rhs));
2249 let m = if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) {
2250 // r + rhs cannot overflow because they have opposite signs
2259 // rhs - m cannot overflow because m has the same sign as rhs
2260 self.checked_add(rhs - m)
2264 /// Returns the logarithm of the number with respect to an arbitrary base,
2267 /// This method might not be optimized owing to implementation details;
2268 /// `ilog2` can produce results more efficiently for base 2, and `ilog10`
2269 /// can produce results more efficiently for base 10.
2273 /// This function will panic if `self` is less than or equal to zero,
2274 /// or if `base` is less then 2.
2279 /// #![feature(int_log)]
2280 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".ilog(5), 1);")]
2282 #[unstable(feature = "int_log", issue = "70887")]
2283 #[must_use = "this returns the result of the operation, \
2284 without modifying the original"]
2287 pub const fn ilog(self, base: Self) -> u32 {
2288 assert!(base >= 2, "base of integer logarithm must be at least 2");
2289 self.checked_ilog(base).expect("argument of integer logarithm must be positive")
2292 /// Returns the base 2 logarithm of the number, rounded down.
2296 /// This function will panic if `self` is less than or equal to zero.
2301 /// #![feature(int_log)]
2302 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".ilog2(), 1);")]
2304 #[unstable(feature = "int_log", issue = "70887")]
2305 #[must_use = "this returns the result of the operation, \
2306 without modifying the original"]
2309 pub const fn ilog2(self) -> u32 {
2310 self.checked_ilog2().expect("argument of integer logarithm must be positive")
2313 /// Returns the base 10 logarithm of the number, rounded down.
2317 /// This function will panic if `self` is less than or equal to zero.
2322 /// #![feature(int_log)]
2323 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".ilog10(), 1);")]
2325 #[unstable(feature = "int_log", issue = "70887")]
2326 #[must_use = "this returns the result of the operation, \
2327 without modifying the original"]
2330 pub const fn ilog10(self) -> u32 {
2331 self.checked_ilog10().expect("argument of integer logarithm must be positive")
2334 /// Returns the logarithm of the number with respect to an arbitrary base,
2337 /// Returns `None` if the number is negative or zero, or if the base is not at least 2.
2339 /// This method might not be optimized owing to implementation details;
2340 /// `checked_ilog2` can produce results more efficiently for base 2, and
2341 /// `checked_ilog10` can produce results more efficiently for base 10.
2346 /// #![feature(int_log)]
2347 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_ilog(5), Some(1));")]
2349 #[unstable(feature = "int_log", issue = "70887")]
2350 #[must_use = "this returns the result of the operation, \
2351 without modifying the original"]
2353 pub const fn checked_ilog(self, base: Self) -> Option<u32> {
2354 if self <= 0 || base <= 1 {
2360 // Optimization for 128 bit wide integers.
2361 if Self::BITS == 128 {
2362 let b = Self::ilog2(self) / (Self::ilog2(base) + 1);
2364 r /= base.pow(b as u32);
2375 /// Returns the base 2 logarithm of the number, rounded down.
2377 /// Returns `None` if the number is negative or zero.
2382 /// #![feature(int_log)]
2383 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_ilog2(), Some(1));")]
2385 #[unstable(feature = "int_log", issue = "70887")]
2386 #[must_use = "this returns the result of the operation, \
2387 without modifying the original"]
2389 pub const fn checked_ilog2(self) -> Option<u32> {
2393 // SAFETY: We just checked that this number is positive
2394 let log = (Self::BITS - 1) - unsafe { intrinsics::ctlz_nonzero(self) as u32 };
2399 /// Returns the base 10 logarithm of the number, rounded down.
2401 /// Returns `None` if the number is negative or zero.
2406 /// #![feature(int_log)]
2407 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_ilog10(), Some(1));")]
2409 #[unstable(feature = "int_log", issue = "70887")]
2410 #[must_use = "this returns the result of the operation, \
2411 without modifying the original"]
2413 pub const fn checked_ilog10(self) -> Option<u32> {
2415 Some(int_log10::$ActualT(self as $ActualT))
2421 /// Computes the absolute value of `self`.
2423 /// # Overflow behavior
2425 /// The absolute value of
2426 #[doc = concat!("`", stringify!($SelfT), "::MIN`")]
2427 /// cannot be represented as an
2428 #[doc = concat!("`", stringify!($SelfT), "`,")]
2429 /// and attempting to calculate it will cause an overflow. This means
2430 /// that code in debug mode will trigger a panic on this case and
2431 /// optimized code will return
2432 #[doc = concat!("`", stringify!($SelfT), "::MIN`")]
2433 /// without a panic.
2440 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".abs(), 10);")]
2441 #[doc = concat!("assert_eq!((-10", stringify!($SelfT), ").abs(), 10);")]
2443 #[stable(feature = "rust1", since = "1.0.0")]
2444 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2445 #[allow(unused_attributes)]
2446 #[must_use = "this returns the result of the operation, \
2447 without modifying the original"]
2449 #[rustc_inherit_overflow_checks]
2450 pub const fn abs(self) -> Self {
2451 // Note that the #[rustc_inherit_overflow_checks] and #[inline]
2452 // above mean that the overflow semantics of the subtraction
2453 // depend on the crate we're being called from.
2454 if self.is_negative() {
2461 /// Computes the absolute difference between `self` and `other`.
2463 /// This function always returns the correct answer without overflow or
2464 /// panics by returning an unsigned integer.
2471 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(80), 20", stringify!($UnsignedT), ");")]
2472 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(110), 10", stringify!($UnsignedT), ");")]
2473 #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").abs_diff(80), 180", stringify!($UnsignedT), ");")]
2474 #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").abs_diff(-120), 20", stringify!($UnsignedT), ");")]
2475 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.abs_diff(", stringify!($SelfT), "::MAX), ", stringify!($UnsignedT), "::MAX);")]
2477 #[stable(feature = "int_abs_diff", since = "1.60.0")]
2478 #[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
2479 #[must_use = "this returns the result of the operation, \
2480 without modifying the original"]
2482 pub const fn abs_diff(self, other: Self) -> $UnsignedT {
2484 // Converting a non-negative x from signed to unsigned by using
2485 // `x as U` is left unchanged, but a negative x is converted
2486 // to value x + 2^N. Thus if `s` and `o` are binary variables
2487 // respectively indicating whether `self` and `other` are
2488 // negative, we are computing the mathematical value:
2490 // (other + o*2^N) - (self + s*2^N) mod 2^N
2491 // other - self + (o-s)*2^N mod 2^N
2492 // other - self mod 2^N
2494 // Finally, taking the mod 2^N of the mathematical value of
2495 // `other - self` does not change it as it already is
2496 // in the range [0, 2^N).
2497 (other as $UnsignedT).wrapping_sub(self as $UnsignedT)
2499 (self as $UnsignedT).wrapping_sub(other as $UnsignedT)
2503 /// Returns a number representing sign of `self`.
2505 /// - `0` if the number is zero
2506 /// - `1` if the number is positive
2507 /// - `-1` if the number is negative
2514 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".signum(), 1);")]
2515 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".signum(), 0);")]
2516 #[doc = concat!("assert_eq!((-10", stringify!($SelfT), ").signum(), -1);")]
2518 #[stable(feature = "rust1", since = "1.0.0")]
2519 #[rustc_const_stable(feature = "const_int_sign", since = "1.47.0")]
2520 #[must_use = "this returns the result of the operation, \
2521 without modifying the original"]
2523 pub const fn signum(self) -> Self {
2531 /// Returns `true` if `self` is positive and `false` if the number is zero or
2539 #[doc = concat!("assert!(10", stringify!($SelfT), ".is_positive());")]
2540 #[doc = concat!("assert!(!(-10", stringify!($SelfT), ").is_positive());")]
2543 #[stable(feature = "rust1", since = "1.0.0")]
2544 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2546 pub const fn is_positive(self) -> bool { self > 0 }
2548 /// Returns `true` if `self` is negative and `false` if the number is zero or
2556 #[doc = concat!("assert!((-10", stringify!($SelfT), ").is_negative());")]
2557 #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_negative());")]
2560 #[stable(feature = "rust1", since = "1.0.0")]
2561 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2563 pub const fn is_negative(self) -> bool { self < 0 }
2565 /// Return the memory representation of this integer as a byte array in
2566 /// big-endian (network) byte order.
2568 #[doc = $to_xe_bytes_doc]
2573 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();")]
2574 #[doc = concat!("assert_eq!(bytes, ", $be_bytes, ");")]
2576 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2577 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2578 #[must_use = "this returns the result of the operation, \
2579 without modifying the original"]
2581 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2582 self.to_be().to_ne_bytes()
2585 /// Return the memory representation of this integer as a byte array in
2586 /// little-endian byte order.
2588 #[doc = $to_xe_bytes_doc]
2593 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();")]
2594 #[doc = concat!("assert_eq!(bytes, ", $le_bytes, ");")]
2596 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2597 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2598 #[must_use = "this returns the result of the operation, \
2599 without modifying the original"]
2601 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2602 self.to_le().to_ne_bytes()
2605 /// Return the memory representation of this integer as a byte array in
2606 /// native byte order.
2608 /// As the target platform's native endianness is used, portable code
2609 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2612 #[doc = $to_xe_bytes_doc]
2614 /// [`to_be_bytes`]: Self::to_be_bytes
2615 /// [`to_le_bytes`]: Self::to_le_bytes
2620 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();")]
2623 /// if cfg!(target_endian = "big") {
2624 #[doc = concat!(" ", $be_bytes)]
2626 #[doc = concat!(" ", $le_bytes)]
2630 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2631 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2632 // SAFETY: const sound because integers are plain old datatypes so we can always
2633 // transmute them to arrays of bytes
2634 #[must_use = "this returns the result of the operation, \
2635 without modifying the original"]
2637 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2638 // SAFETY: integers are plain old datatypes so we can always transmute them to
2640 unsafe { mem::transmute(self) }
2643 /// Create an integer value from its representation as a byte array in
2646 #[doc = $from_xe_bytes_doc]
2651 #[doc = concat!("let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");")]
2652 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2655 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2658 #[doc = concat!("fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2659 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2661 #[doc = concat!(" ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())")]
2664 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2665 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2668 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2669 Self::from_be(Self::from_ne_bytes(bytes))
2672 /// Create an integer value from its representation as a byte array in
2675 #[doc = $from_xe_bytes_doc]
2680 #[doc = concat!("let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");")]
2681 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2684 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2687 #[doc = concat!("fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2688 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2690 #[doc = concat!(" ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())")]
2693 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2694 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2697 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2698 Self::from_le(Self::from_ne_bytes(bytes))
2701 /// Create an integer value from its memory representation as a byte
2702 /// array in native endianness.
2704 /// As the target platform's native endianness is used, portable code
2705 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2706 /// appropriate instead.
2708 /// [`from_be_bytes`]: Self::from_be_bytes
2709 /// [`from_le_bytes`]: Self::from_le_bytes
2711 #[doc = $from_xe_bytes_doc]
2716 #[doc = concat!("let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {")]
2717 #[doc = concat!(" ", $be_bytes)]
2719 #[doc = concat!(" ", $le_bytes)]
2721 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2724 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2727 #[doc = concat!("fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2728 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2730 #[doc = concat!(" ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())")]
2733 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2734 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2736 // SAFETY: const sound because integers are plain old datatypes so we can always
2737 // transmute to them
2739 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2740 // SAFETY: integers are plain old datatypes so we can always transmute to them
2741 unsafe { mem::transmute(bytes) }
2744 /// New code should prefer to use
2745 #[doc = concat!("[`", stringify!($SelfT), "::MIN", "`] instead.")]
2747 /// Returns the smallest value that can be represented by this integer type.
2748 #[stable(feature = "rust1", since = "1.0.0")]
2751 #[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
2752 #[deprecated(since = "TBD", note = "replaced by the `MIN` associated constant on this type")]
2753 pub const fn min_value() -> Self {
2757 /// New code should prefer to use
2758 #[doc = concat!("[`", stringify!($SelfT), "::MAX", "`] instead.")]
2760 /// Returns the largest value that can be represented by this integer type.
2761 #[stable(feature = "rust1", since = "1.0.0")]
2764 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2765 #[deprecated(since = "TBD", note = "replaced by the `MAX` associated constant on this type")]
2766 pub const fn max_value() -> Self {