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`.
110 /// Depending on what you're doing with the value, you might also be interested in the
111 /// [`ilog2`] function which returns a consistent number, even if the type widens.
118 #[doc = concat!("let n = -1", stringify!($SelfT), ";")]
120 /// assert_eq!(n.leading_zeros(), 0);
122 #[doc = concat!("[`ilog2`]: ", stringify!($SelfT), "::ilog2")]
123 #[stable(feature = "rust1", since = "1.0.0")]
124 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
125 #[must_use = "this returns the result of the operation, \
126 without modifying the original"]
128 pub const fn leading_zeros(self) -> u32 {
129 (self as $UnsignedT).leading_zeros()
132 /// Returns the number of trailing zeros in the binary representation of `self`.
139 #[doc = concat!("let n = -4", stringify!($SelfT), ";")]
141 /// assert_eq!(n.trailing_zeros(), 2);
143 #[stable(feature = "rust1", since = "1.0.0")]
144 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
145 #[must_use = "this returns the result of the operation, \
146 without modifying the original"]
148 pub const fn trailing_zeros(self) -> u32 {
149 (self as $UnsignedT).trailing_zeros()
152 /// Returns the number of leading ones in the binary representation of `self`.
159 #[doc = concat!("let n = -1", stringify!($SelfT), ";")]
161 #[doc = concat!("assert_eq!(n.leading_ones(), ", stringify!($BITS), ");")]
163 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
164 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
165 #[must_use = "this returns the result of the operation, \
166 without modifying the original"]
168 pub const fn leading_ones(self) -> u32 {
169 (self as $UnsignedT).leading_ones()
172 /// Returns the number of trailing ones in the binary representation of `self`.
179 #[doc = concat!("let n = 3", stringify!($SelfT), ";")]
181 /// assert_eq!(n.trailing_ones(), 2);
183 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
184 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
185 #[must_use = "this returns the result of the operation, \
186 without modifying the original"]
188 pub const fn trailing_ones(self) -> u32 {
189 (self as $UnsignedT).trailing_ones()
192 /// Shifts the bits to the left by a specified amount, `n`,
193 /// wrapping the truncated bits to the end of the resulting integer.
195 /// Please note this isn't the same operation as the `<<` shifting operator!
202 #[doc = concat!("let n = ", $rot_op, stringify!($SelfT), ";")]
203 #[doc = concat!("let m = ", $rot_result, ";")]
205 #[doc = concat!("assert_eq!(n.rotate_left(", $rot, "), m);")]
207 #[stable(feature = "rust1", since = "1.0.0")]
208 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
209 #[must_use = "this returns the result of the operation, \
210 without modifying the original"]
212 pub const fn rotate_left(self, n: u32) -> Self {
213 (self as $UnsignedT).rotate_left(n) as Self
216 /// Shifts the bits to the right by a specified amount, `n`,
217 /// wrapping the truncated bits to the beginning of the resulting
220 /// Please note this isn't the same operation as the `>>` shifting operator!
227 #[doc = concat!("let n = ", $rot_result, stringify!($SelfT), ";")]
228 #[doc = concat!("let m = ", $rot_op, ";")]
230 #[doc = concat!("assert_eq!(n.rotate_right(", $rot, "), m);")]
232 #[stable(feature = "rust1", since = "1.0.0")]
233 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
234 #[must_use = "this returns the result of the operation, \
235 without modifying the original"]
237 pub const fn rotate_right(self, n: u32) -> Self {
238 (self as $UnsignedT).rotate_right(n) as Self
241 /// Reverses the byte order of the integer.
248 #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
250 /// let m = n.swap_bytes();
252 #[doc = concat!("assert_eq!(m, ", $swapped, ");")]
254 #[stable(feature = "rust1", since = "1.0.0")]
255 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
256 #[must_use = "this returns the result of the operation, \
257 without modifying the original"]
259 pub const fn swap_bytes(self) -> Self {
260 (self as $UnsignedT).swap_bytes() as Self
263 /// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
264 /// second least-significant bit becomes second most-significant bit, etc.
271 #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
272 /// let m = n.reverse_bits();
274 #[doc = concat!("assert_eq!(m, ", $reversed, ");")]
275 #[doc = concat!("assert_eq!(0, 0", stringify!($SelfT), ".reverse_bits());")]
277 #[stable(feature = "reverse_bits", since = "1.37.0")]
278 #[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
279 #[must_use = "this returns the result of the operation, \
280 without modifying the original"]
282 pub const fn reverse_bits(self) -> Self {
283 (self as $UnsignedT).reverse_bits() as Self
286 /// Converts an integer from big endian to the target's endianness.
288 /// On big endian this is a no-op. On little endian the bytes are swapped.
295 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
297 /// if cfg!(target_endian = "big") {
298 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_be(n), n)")]
300 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())")]
303 #[stable(feature = "rust1", since = "1.0.0")]
304 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
307 pub const fn from_be(x: Self) -> Self {
308 #[cfg(target_endian = "big")]
312 #[cfg(not(target_endian = "big"))]
318 /// Converts an integer from little endian to the target's endianness.
320 /// On little endian this is a no-op. On big endian the bytes are swapped.
327 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
329 /// if cfg!(target_endian = "little") {
330 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_le(n), n)")]
332 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())")]
335 #[stable(feature = "rust1", since = "1.0.0")]
336 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
339 pub const fn from_le(x: Self) -> Self {
340 #[cfg(target_endian = "little")]
344 #[cfg(not(target_endian = "little"))]
350 /// Converts `self` to big endian from the target's endianness.
352 /// On big endian this is a no-op. On little endian the bytes are swapped.
359 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
361 /// if cfg!(target_endian = "big") {
362 /// assert_eq!(n.to_be(), n)
364 /// assert_eq!(n.to_be(), n.swap_bytes())
367 #[stable(feature = "rust1", since = "1.0.0")]
368 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
369 #[must_use = "this returns the result of the operation, \
370 without modifying the original"]
372 pub const fn to_be(self) -> Self { // or not to be?
373 #[cfg(target_endian = "big")]
377 #[cfg(not(target_endian = "big"))]
383 /// Converts `self` to little endian from the target's endianness.
385 /// On little endian this is a no-op. On big endian the bytes are swapped.
392 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
394 /// if cfg!(target_endian = "little") {
395 /// assert_eq!(n.to_le(), n)
397 /// assert_eq!(n.to_le(), n.swap_bytes())
400 #[stable(feature = "rust1", since = "1.0.0")]
401 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
402 #[must_use = "this returns the result of the operation, \
403 without modifying the original"]
405 pub const fn to_le(self) -> Self {
406 #[cfg(target_endian = "little")]
410 #[cfg(not(target_endian = "little"))]
416 /// Checked integer addition. Computes `self + rhs`, returning `None`
417 /// if overflow occurred.
424 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(1), Some(", stringify!($SelfT), "::MAX - 1));")]
425 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);")]
427 #[stable(feature = "rust1", since = "1.0.0")]
428 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
429 #[must_use = "this returns the result of the operation, \
430 without modifying the original"]
432 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
433 let (a, b) = self.overflowing_add(rhs);
434 if unlikely!(b) {None} else {Some(a)}
437 /// Unchecked integer addition. Computes `self + rhs`, assuming overflow
442 /// This results in undefined behavior when
443 #[doc = concat!("`self + rhs > ", stringify!($SelfT), "::MAX` or `self + rhs < ", stringify!($SelfT), "::MIN`,")]
444 /// i.e. when [`checked_add`] would return `None`.
446 #[doc = concat!("[`checked_add`]: ", stringify!($SelfT), "::checked_add")]
448 feature = "unchecked_math",
449 reason = "niche optimization path",
452 #[must_use = "this returns the result of the operation, \
453 without modifying the original"]
454 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
456 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
457 pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
458 // SAFETY: the caller must uphold the safety contract for
460 unsafe { intrinsics::unchecked_add(self, rhs) }
463 /// Checked addition with an unsigned integer. Computes `self + rhs`,
464 /// returning `None` if overflow occurred.
471 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_add_unsigned(2), Some(3));")]
472 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add_unsigned(3), None);")]
474 #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
475 #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
476 #[must_use = "this returns the result of the operation, \
477 without modifying the original"]
479 pub const fn checked_add_unsigned(self, rhs: $UnsignedT) -> Option<Self> {
480 let (a, b) = self.overflowing_add_unsigned(rhs);
481 if unlikely!(b) {None} else {Some(a)}
484 /// Checked integer subtraction. Computes `self - rhs`, returning `None` if
485 /// overflow occurred.
492 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 2).checked_sub(1), Some(", stringify!($SelfT), "::MIN + 1));")]
493 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 2).checked_sub(3), None);")]
495 #[stable(feature = "rust1", since = "1.0.0")]
496 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
497 #[must_use = "this returns the result of the operation, \
498 without modifying the original"]
500 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
501 let (a, b) = self.overflowing_sub(rhs);
502 if unlikely!(b) {None} else {Some(a)}
505 /// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
510 /// This results in undefined behavior when
511 #[doc = concat!("`self - rhs > ", stringify!($SelfT), "::MAX` or `self - rhs < ", stringify!($SelfT), "::MIN`,")]
512 /// i.e. when [`checked_sub`] would return `None`.
514 #[doc = concat!("[`checked_sub`]: ", stringify!($SelfT), "::checked_sub")]
516 feature = "unchecked_math",
517 reason = "niche optimization path",
520 #[must_use = "this returns the result of the operation, \
521 without modifying the original"]
522 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
524 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
525 pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
526 // SAFETY: the caller must uphold the safety contract for
528 unsafe { intrinsics::unchecked_sub(self, rhs) }
531 /// Checked subtraction with an unsigned integer. Computes `self - rhs`,
532 /// returning `None` if overflow occurred.
539 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_sub_unsigned(2), Some(-1));")]
540 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 2).checked_sub_unsigned(3), None);")]
542 #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
543 #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
544 #[must_use = "this returns the result of the operation, \
545 without modifying the original"]
547 pub const fn checked_sub_unsigned(self, rhs: $UnsignedT) -> Option<Self> {
548 let (a, b) = self.overflowing_sub_unsigned(rhs);
549 if unlikely!(b) {None} else {Some(a)}
552 /// Checked integer multiplication. Computes `self * rhs`, returning `None` if
553 /// overflow occurred.
560 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(1), Some(", stringify!($SelfT), "::MAX));")]
561 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);")]
563 #[stable(feature = "rust1", since = "1.0.0")]
564 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
565 #[must_use = "this returns the result of the operation, \
566 without modifying the original"]
568 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
569 let (a, b) = self.overflowing_mul(rhs);
570 if unlikely!(b) {None} else {Some(a)}
573 /// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
578 /// This results in undefined behavior when
579 #[doc = concat!("`self * rhs > ", stringify!($SelfT), "::MAX` or `self * rhs < ", stringify!($SelfT), "::MIN`,")]
580 /// i.e. when [`checked_mul`] would return `None`.
582 #[doc = concat!("[`checked_mul`]: ", stringify!($SelfT), "::checked_mul")]
584 feature = "unchecked_math",
585 reason = "niche optimization path",
588 #[must_use = "this returns the result of the operation, \
589 without modifying the original"]
590 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
592 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
593 pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
594 // SAFETY: the caller must uphold the safety contract for
596 unsafe { intrinsics::unchecked_mul(self, rhs) }
599 /// Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
600 /// or the division results in overflow.
607 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 1).checked_div(-1), Some(", stringify!($Max), "));")]
608 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_div(-1), None);")]
609 #[doc = concat!("assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);")]
611 #[stable(feature = "rust1", since = "1.0.0")]
612 #[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
613 #[must_use = "this returns the result of the operation, \
614 without modifying the original"]
616 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
617 if unlikely!(rhs == 0 || ((self == Self::MIN) && (rhs == -1))) {
620 // SAFETY: div by zero and by INT_MIN have been checked above
621 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
625 /// Checked Euclidean division. Computes `self.div_euclid(rhs)`,
626 /// returning `None` if `rhs == 0` or the division results in overflow.
633 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 1).checked_div_euclid(-1), Some(", stringify!($Max), "));")]
634 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_div_euclid(-1), None);")]
635 #[doc = concat!("assert_eq!((1", stringify!($SelfT), ").checked_div_euclid(0), None);")]
637 #[stable(feature = "euclidean_division", since = "1.38.0")]
638 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
639 #[must_use = "this returns the result of the operation, \
640 without modifying the original"]
642 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
643 // Using `&` helps LLVM see that it is the same check made in division.
644 if unlikely!(rhs == 0 || ((self == Self::MIN) & (rhs == -1))) {
647 Some(self.div_euclid(rhs))
651 /// Checked integer remainder. Computes `self % rhs`, returning `None` if
652 /// `rhs == 0` or the division results in overflow.
659 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));")]
660 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);")]
661 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);")]
663 #[stable(feature = "wrapping", since = "1.7.0")]
664 #[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
665 #[must_use = "this returns the result of the operation, \
666 without modifying the original"]
668 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
669 if unlikely!(rhs == 0 || ((self == Self::MIN) && (rhs == -1))) {
672 // SAFETY: div by zero and by INT_MIN have been checked above
673 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
677 /// Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`
678 /// if `rhs == 0` or the division results in overflow.
685 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));")]
686 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);")]
687 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_rem_euclid(-1), None);")]
689 #[stable(feature = "euclidean_division", since = "1.38.0")]
690 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
691 #[must_use = "this returns the result of the operation, \
692 without modifying the original"]
694 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
695 // Using `&` helps LLVM see that it is the same check made in division.
696 if unlikely!(rhs == 0 || ((self == Self::MIN) & (rhs == -1))) {
699 Some(self.rem_euclid(rhs))
703 /// Checked negation. Computes `-self`, returning `None` if `self == MIN`.
710 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));")]
711 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);")]
713 #[stable(feature = "wrapping", since = "1.7.0")]
714 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
715 #[must_use = "this returns the result of the operation, \
716 without modifying the original"]
718 pub const fn checked_neg(self) -> Option<Self> {
719 let (a, b) = self.overflowing_neg();
720 if unlikely!(b) {None} else {Some(a)}
723 /// Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
724 /// than or equal to the number of bits in `self`.
731 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));")]
732 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);")]
734 #[stable(feature = "wrapping", since = "1.7.0")]
735 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
736 #[must_use = "this returns the result of the operation, \
737 without modifying the original"]
739 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
740 let (a, b) = self.overflowing_shl(rhs);
741 if unlikely!(b) {None} else {Some(a)}
744 /// Unchecked shift left. Computes `self << rhs`, assuming that
745 /// `rhs` is less than the number of bits in `self`.
749 /// This results in undefined behavior if `rhs` is larger than
750 /// or equal to the number of bits in `self`,
751 /// i.e. when [`checked_shl`] would return `None`.
753 #[doc = concat!("[`checked_shl`]: ", stringify!($SelfT), "::checked_shl")]
755 feature = "unchecked_math",
756 reason = "niche optimization path",
759 #[must_use = "this returns the result of the operation, \
760 without modifying the original"]
761 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
763 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
764 pub const unsafe fn unchecked_shl(self, rhs: u32) -> Self {
765 // SAFETY: the caller must uphold the safety contract for
767 // Any legal shift amount is losslessly representable in the self type.
768 unsafe { intrinsics::unchecked_shl(self, rhs.try_into().ok().unwrap_unchecked()) }
771 /// Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
772 /// larger than or equal to the number of bits in `self`.
779 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));")]
780 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);")]
782 #[stable(feature = "wrapping", since = "1.7.0")]
783 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
784 #[must_use = "this returns the result of the operation, \
785 without modifying the original"]
787 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
788 let (a, b) = self.overflowing_shr(rhs);
789 if unlikely!(b) {None} else {Some(a)}
792 /// Unchecked shift right. Computes `self >> rhs`, assuming that
793 /// `rhs` is less than the number of bits in `self`.
797 /// This results in undefined behavior if `rhs` is larger than
798 /// or equal to the number of bits in `self`,
799 /// i.e. when [`checked_shr`] would return `None`.
801 #[doc = concat!("[`checked_shr`]: ", stringify!($SelfT), "::checked_shr")]
803 feature = "unchecked_math",
804 reason = "niche optimization path",
807 #[must_use = "this returns the result of the operation, \
808 without modifying the original"]
809 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
811 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
812 pub const unsafe fn unchecked_shr(self, rhs: u32) -> Self {
813 // SAFETY: the caller must uphold the safety contract for
815 // Any legal shift amount is losslessly representable in the self type.
816 unsafe { intrinsics::unchecked_shr(self, rhs.try_into().ok().unwrap_unchecked()) }
819 /// Checked absolute value. Computes `self.abs()`, returning `None` if
827 #[doc = concat!("assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));")]
828 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);")]
830 #[stable(feature = "no_panic_abs", since = "1.13.0")]
831 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
832 #[must_use = "this returns the result of the operation, \
833 without modifying the original"]
835 pub const fn checked_abs(self) -> Option<Self> {
836 if self.is_negative() {
843 /// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
844 /// overflow occurred.
851 #[doc = concat!("assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));")]
852 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);")]
855 #[stable(feature = "no_panic_pow", since = "1.34.0")]
856 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
857 #[must_use = "this returns the result of the operation, \
858 without modifying the original"]
860 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
865 let mut acc: Self = 1;
869 acc = try_opt!(acc.checked_mul(base));
872 base = try_opt!(base.checked_mul(base));
874 // since exp!=0, finally the exp must be 1.
875 // Deal with the final bit of the exponent separately, since
876 // squaring the base afterwards is not necessary and may cause a
877 // needless overflow.
878 acc.checked_mul(base)
881 /// Saturating integer addition. Computes `self + rhs`, saturating at the numeric
882 /// bounds instead of overflowing.
889 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);")]
890 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(100), ", stringify!($SelfT), "::MAX);")]
891 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_add(-1), ", stringify!($SelfT), "::MIN);")]
894 #[stable(feature = "rust1", since = "1.0.0")]
895 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
896 #[must_use = "this returns the result of the operation, \
897 without modifying the original"]
899 pub const fn saturating_add(self, rhs: Self) -> Self {
900 intrinsics::saturating_add(self, rhs)
903 /// Saturating addition with an unsigned integer. Computes `self + rhs`,
904 /// saturating at the numeric bounds instead of overflowing.
911 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_unsigned(2), 3);")]
912 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add_unsigned(100), ", stringify!($SelfT), "::MAX);")]
914 #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
915 #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
916 #[must_use = "this returns the result of the operation, \
917 without modifying the original"]
919 pub const fn saturating_add_unsigned(self, rhs: $UnsignedT) -> Self {
920 // Overflow can only happen at the upper bound
921 // We cannot use `unwrap_or` here because it is not `const`
922 match self.checked_add_unsigned(rhs) {
928 /// Saturating integer subtraction. Computes `self - rhs`, saturating at the
929 /// numeric bounds instead of overflowing.
936 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);")]
937 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_sub(100), ", stringify!($SelfT), "::MIN);")]
938 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_sub(-1), ", stringify!($SelfT), "::MAX);")]
940 #[stable(feature = "rust1", since = "1.0.0")]
941 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
942 #[must_use = "this returns the result of the operation, \
943 without modifying the original"]
945 pub const fn saturating_sub(self, rhs: Self) -> Self {
946 intrinsics::saturating_sub(self, rhs)
949 /// Saturating subtraction with an unsigned integer. Computes `self - rhs`,
950 /// saturating at the numeric bounds instead of overflowing.
957 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_sub_unsigned(127), -27);")]
958 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_sub_unsigned(100), ", stringify!($SelfT), "::MIN);")]
960 #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
961 #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
962 #[must_use = "this returns the result of the operation, \
963 without modifying the original"]
965 pub const fn saturating_sub_unsigned(self, rhs: $UnsignedT) -> Self {
966 // Overflow can only happen at the lower bound
967 // We cannot use `unwrap_or` here because it is not `const`
968 match self.checked_sub_unsigned(rhs) {
974 /// Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
975 /// instead of overflowing.
982 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_neg(), -100);")]
983 #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").saturating_neg(), 100);")]
984 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_neg(), ", stringify!($SelfT), "::MAX);")]
985 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_neg(), ", stringify!($SelfT), "::MIN + 1);")]
988 #[stable(feature = "saturating_neg", since = "1.45.0")]
989 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
990 #[must_use = "this returns the result of the operation, \
991 without modifying the original"]
993 pub const fn saturating_neg(self) -> Self {
994 intrinsics::saturating_sub(0, self)
997 /// Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
998 /// MIN` instead of overflowing.
1005 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_abs(), 100);")]
1006 #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").saturating_abs(), 100);")]
1007 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_abs(), ", stringify!($SelfT), "::MAX);")]
1008 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 1).saturating_abs(), ", stringify!($SelfT), "::MAX);")]
1011 #[stable(feature = "saturating_neg", since = "1.45.0")]
1012 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1013 #[must_use = "this returns the result of the operation, \
1014 without modifying the original"]
1016 pub const fn saturating_abs(self) -> Self {
1017 if self.is_negative() {
1018 self.saturating_neg()
1024 /// Saturating integer multiplication. Computes `self * rhs`, saturating at the
1025 /// numeric bounds instead of overflowing.
1032 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);")]
1033 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);")]
1034 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);")]
1036 #[stable(feature = "wrapping", since = "1.7.0")]
1037 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1038 #[must_use = "this returns the result of the operation, \
1039 without modifying the original"]
1041 pub const fn saturating_mul(self, rhs: Self) -> Self {
1042 match self.checked_mul(rhs) {
1044 None => if (self < 0) == (rhs < 0) {
1052 /// Saturating integer division. Computes `self / rhs`, saturating at the
1053 /// numeric bounds instead of overflowing.
1060 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".saturating_div(2), 2);")]
1061 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_div(-1), ", stringify!($SelfT), "::MIN + 1);")]
1062 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_div(-1), ", stringify!($SelfT), "::MAX);")]
1067 #[doc = concat!("let _ = 1", stringify!($SelfT), ".saturating_div(0);")]
1070 #[stable(feature = "saturating_div", since = "1.58.0")]
1071 #[rustc_const_stable(feature = "saturating_div", since = "1.58.0")]
1072 #[must_use = "this returns the result of the operation, \
1073 without modifying the original"]
1075 pub const fn saturating_div(self, rhs: Self) -> Self {
1076 match self.overflowing_div(rhs) {
1077 (result, false) => result,
1078 (_result, true) => Self::MAX, // MIN / -1 is the only possible saturating overflow
1082 /// Saturating integer exponentiation. Computes `self.pow(exp)`,
1083 /// saturating at the numeric bounds instead of overflowing.
1090 #[doc = concat!("assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);")]
1091 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);")]
1092 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);")]
1094 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1095 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1096 #[must_use = "this returns the result of the operation, \
1097 without modifying the original"]
1099 pub const fn saturating_pow(self, exp: u32) -> Self {
1100 match self.checked_pow(exp) {
1102 None if self < 0 && exp % 2 == 1 => Self::MIN,
1107 /// Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
1108 /// boundary of the type.
1115 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);")]
1116 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_add(2), ", stringify!($SelfT), "::MIN + 1);")]
1118 #[stable(feature = "rust1", since = "1.0.0")]
1119 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1120 #[must_use = "this returns the result of the operation, \
1121 without modifying the original"]
1123 pub const fn wrapping_add(self, rhs: Self) -> Self {
1124 intrinsics::wrapping_add(self, rhs)
1127 /// Wrapping (modular) addition with an unsigned integer. Computes
1128 /// `self + rhs`, wrapping around at the boundary of the type.
1135 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_add_unsigned(27), 127);")]
1136 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_add_unsigned(2), ", stringify!($SelfT), "::MIN + 1);")]
1138 #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
1139 #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
1140 #[must_use = "this returns the result of the operation, \
1141 without modifying the original"]
1143 pub const fn wrapping_add_unsigned(self, rhs: $UnsignedT) -> Self {
1144 self.wrapping_add(rhs as Self)
1147 /// Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1148 /// boundary of the type.
1155 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);")]
1156 #[doc = concat!("assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::MAX), ", stringify!($SelfT), "::MAX);")]
1158 #[stable(feature = "rust1", since = "1.0.0")]
1159 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1160 #[must_use = "this returns the result of the operation, \
1161 without modifying the original"]
1163 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1164 intrinsics::wrapping_sub(self, rhs)
1167 /// Wrapping (modular) subtraction with an unsigned integer. Computes
1168 /// `self - rhs`, wrapping around at the boundary of the type.
1175 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".wrapping_sub_unsigned(127), -127);")]
1176 #[doc = concat!("assert_eq!((-2", stringify!($SelfT), ").wrapping_sub_unsigned(", stringify!($UnsignedT), "::MAX), -1);")]
1178 #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
1179 #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
1180 #[must_use = "this returns the result of the operation, \
1181 without modifying the original"]
1183 pub const fn wrapping_sub_unsigned(self, rhs: $UnsignedT) -> Self {
1184 self.wrapping_sub(rhs as Self)
1187 /// Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1188 /// the boundary of the type.
1195 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);")]
1196 /// assert_eq!(11i8.wrapping_mul(12), -124);
1198 #[stable(feature = "rust1", since = "1.0.0")]
1199 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1200 #[must_use = "this returns the result of the operation, \
1201 without modifying the original"]
1203 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1204 intrinsics::wrapping_mul(self, rhs)
1207 /// Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1208 /// boundary of the type.
1210 /// The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1211 /// `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1212 /// that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1216 /// This function will panic if `rhs` is 0.
1223 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);")]
1224 /// assert_eq!((-128i8).wrapping_div(-1), -128);
1226 #[stable(feature = "num_wrapping", since = "1.2.0")]
1227 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1228 #[must_use = "this returns the result of the operation, \
1229 without modifying the original"]
1231 pub const fn wrapping_div(self, rhs: Self) -> Self {
1232 self.overflowing_div(rhs).0
1235 /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
1236 /// wrapping around at the boundary of the type.
1238 /// Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1239 /// for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1240 /// type. In this case, this method returns `MIN` itself.
1244 /// This function will panic if `rhs` is 0.
1251 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);")]
1252 /// assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
1254 #[stable(feature = "euclidean_division", since = "1.38.0")]
1255 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1256 #[must_use = "this returns the result of the operation, \
1257 without modifying the original"]
1259 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
1260 self.overflowing_div_euclid(rhs).0
1263 /// Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1264 /// boundary of the type.
1266 /// Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1267 /// invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1268 /// this function returns `0`.
1272 /// This function will panic if `rhs` is 0.
1279 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);")]
1280 /// assert_eq!((-128i8).wrapping_rem(-1), 0);
1282 #[stable(feature = "num_wrapping", since = "1.2.0")]
1283 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1284 #[must_use = "this returns the result of the operation, \
1285 without modifying the original"]
1287 pub const fn wrapping_rem(self, rhs: Self) -> Self {
1288 self.overflowing_rem(rhs).0
1291 /// Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
1292 /// at the boundary of the type.
1294 /// Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1295 /// for the type). In this case, this method returns 0.
1299 /// This function will panic if `rhs` is 0.
1306 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);")]
1307 /// assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
1309 #[stable(feature = "euclidean_division", since = "1.38.0")]
1310 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1311 #[must_use = "this returns the result of the operation, \
1312 without modifying the original"]
1314 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1315 self.overflowing_rem_euclid(rhs).0
1318 /// Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1321 /// The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1322 /// is the negative minimal value for the type); this is a positive value that is too large to represent
1323 /// in the type. In such a case, this function returns `MIN` itself.
1330 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);")]
1331 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.wrapping_neg(), ", stringify!($SelfT), "::MIN);")]
1333 #[stable(feature = "num_wrapping", since = "1.2.0")]
1334 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1335 #[must_use = "this returns the result of the operation, \
1336 without modifying the original"]
1338 pub const fn wrapping_neg(self) -> Self {
1339 (0 as $SelfT).wrapping_sub(self)
1342 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1343 /// any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1345 /// Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1346 /// the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1347 /// The primitive integer types all implement a [`rotate_left`](Self::rotate_left) function,
1348 /// which may be what you want instead.
1355 #[doc = concat!("assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);")]
1356 #[doc = concat!("assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);")]
1358 #[stable(feature = "num_wrapping", since = "1.2.0")]
1359 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1360 #[must_use = "this returns the result of the operation, \
1361 without modifying the original"]
1363 #[rustc_allow_const_fn_unstable(const_inherent_unchecked_arith)]
1364 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1365 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1368 self.unchecked_shl(rhs & ($BITS - 1))
1372 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1373 /// removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1375 /// Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1376 /// to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1377 /// end. The primitive integer types all implement a [`rotate_right`](Self::rotate_right) function,
1378 /// which may be what you want instead.
1385 #[doc = concat!("assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);")]
1386 /// assert_eq!((-128i16).wrapping_shr(64), -128);
1388 #[stable(feature = "num_wrapping", since = "1.2.0")]
1389 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1390 #[must_use = "this returns the result of the operation, \
1391 without modifying the original"]
1393 #[rustc_allow_const_fn_unstable(const_inherent_unchecked_arith)]
1394 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1395 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1398 self.unchecked_shr(rhs & ($BITS - 1))
1402 /// Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1403 /// the boundary of the type.
1405 /// The only case where such wrapping can occur is when one takes the absolute value of the negative
1406 /// minimal value for the type; this is a positive value that is too large to represent in the type. In
1407 /// such a case, this function returns `MIN` itself.
1414 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);")]
1415 #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);")]
1416 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.wrapping_abs(), ", stringify!($SelfT), "::MIN);")]
1417 /// assert_eq!((-128i8).wrapping_abs() as u8, 128);
1419 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1420 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1421 #[must_use = "this returns the result of the operation, \
1422 without modifying the original"]
1423 #[allow(unused_attributes)]
1425 pub const fn wrapping_abs(self) -> Self {
1426 if self.is_negative() {
1433 /// Computes the absolute value of `self` without any wrapping
1442 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".unsigned_abs(), 100", stringify!($UnsignedT), ");")]
1443 #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").unsigned_abs(), 100", stringify!($UnsignedT), ");")]
1444 /// assert_eq!((-128i8).unsigned_abs(), 128u8);
1446 #[stable(feature = "unsigned_abs", since = "1.51.0")]
1447 #[rustc_const_stable(feature = "unsigned_abs", since = "1.51.0")]
1448 #[must_use = "this returns the result of the operation, \
1449 without modifying the original"]
1451 pub const fn unsigned_abs(self) -> $UnsignedT {
1452 self.wrapping_abs() as $UnsignedT
1455 /// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1456 /// wrapping around at the boundary of the type.
1463 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);")]
1464 /// assert_eq!(3i8.wrapping_pow(5), -13);
1465 /// assert_eq!(3i8.wrapping_pow(6), -39);
1467 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1468 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1469 #[must_use = "this returns the result of the operation, \
1470 without modifying the original"]
1472 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
1476 let mut base = self;
1477 let mut acc: Self = 1;
1481 acc = acc.wrapping_mul(base);
1484 base = base.wrapping_mul(base);
1487 // since exp!=0, finally the exp must be 1.
1488 // Deal with the final bit of the exponent separately, since
1489 // squaring the base afterwards is not necessary and may cause a
1490 // needless overflow.
1491 acc.wrapping_mul(base)
1494 /// Calculates `self` + `rhs`
1496 /// Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1497 /// occur. If an overflow would have occurred then the wrapped value is returned.
1504 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));")]
1505 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT), "::MIN, true));")]
1507 #[stable(feature = "wrapping", since = "1.7.0")]
1508 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1509 #[must_use = "this returns the result of the operation, \
1510 without modifying the original"]
1512 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1513 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1517 /// Calculates `self` + `rhs` + `carry` and checks for overflow.
1519 /// Performs "ternary addition" of two integer operands and a carry-in
1520 /// bit, and returns a tuple of the sum along with a boolean indicating
1521 /// whether an arithmetic overflow would occur. On overflow, the wrapped
1522 /// value is returned.
1524 /// This allows chaining together multiple additions to create a wider
1525 /// addition, and can be useful for bignum addition. This method should
1526 /// only be used for the most significant word; for the less significant
1527 /// words the unsigned method
1528 #[doc = concat!("[`", stringify!($UnsignedT), "::carrying_add`]")]
1531 /// The output boolean returned by this method is *not* a carry flag,
1532 /// and should *not* be added to a more significant word.
1534 /// If the input carry is false, this method is equivalent to
1535 /// [`overflowing_add`](Self::overflowing_add).
1540 /// #![feature(bigint_helper_methods)]
1541 /// // Only the most significant word is signed.
1543 #[doc = concat!("// 10 MAX (a = 10 × 2^", stringify!($BITS), " + 2^", stringify!($BITS), " - 1)")]
1544 #[doc = concat!("// + -5 9 (b = -5 × 2^", stringify!($BITS), " + 9)")]
1546 #[doc = concat!("// 6 8 (sum = 6 × 2^", stringify!($BITS), " + 8)")]
1548 #[doc = concat!("let (a1, a0): (", stringify!($SelfT), ", ", stringify!($UnsignedT), ") = (10, ", stringify!($UnsignedT), "::MAX);")]
1549 #[doc = concat!("let (b1, b0): (", stringify!($SelfT), ", ", stringify!($UnsignedT), ") = (-5, 9);")]
1550 /// let carry0 = false;
1552 #[doc = concat!("// ", stringify!($UnsignedT), "::carrying_add for the less significant words")]
1553 /// let (sum0, carry1) = a0.carrying_add(b0, carry0);
1554 /// assert_eq!(carry1, true);
1556 #[doc = concat!("// ", stringify!($SelfT), "::carrying_add for the most significant word")]
1557 /// let (sum1, overflow) = a1.carrying_add(b1, carry1);
1558 /// assert_eq!(overflow, false);
1560 /// assert_eq!((sum1, sum0), (6, 8));
1562 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
1563 #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")]
1564 #[must_use = "this returns the result of the operation, \
1565 without modifying the original"]
1567 pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
1568 // note: longer-term this should be done via an intrinsic.
1569 // note: no intermediate overflow is required (https://github.com/rust-lang/rust/issues/85532#issuecomment-1032214946).
1570 let (a, b) = self.overflowing_add(rhs);
1571 let (c, d) = a.overflowing_add(carry as $SelfT);
1575 /// Calculates `self` + `rhs` with an unsigned `rhs`
1577 /// Returns a tuple of the addition along with a boolean indicating
1578 /// whether an arithmetic overflow would occur. If an overflow would
1579 /// have occurred then the wrapped value is returned.
1586 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_unsigned(2), (3, false));")]
1587 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN).overflowing_add_unsigned(", stringify!($UnsignedT), "::MAX), (", stringify!($SelfT), "::MAX, false));")]
1588 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).overflowing_add_unsigned(3), (", stringify!($SelfT), "::MIN, true));")]
1590 #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
1591 #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
1592 #[must_use = "this returns the result of the operation, \
1593 without modifying the original"]
1595 pub const fn overflowing_add_unsigned(self, rhs: $UnsignedT) -> (Self, bool) {
1596 let rhs = rhs as Self;
1597 let (res, overflowed) = self.overflowing_add(rhs);
1598 (res, overflowed ^ (rhs < 0))
1601 /// Calculates `self` - `rhs`
1603 /// Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1604 /// would occur. If an overflow would have occurred then the wrapped value is returned.
1611 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));")]
1612 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")]
1614 #[stable(feature = "wrapping", since = "1.7.0")]
1615 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1616 #[must_use = "this returns the result of the operation, \
1617 without modifying the original"]
1619 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1620 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1624 /// Calculates `self` − `rhs` − `borrow` and checks for
1627 /// Performs "ternary subtraction" by subtracting both an integer
1628 /// operand and a borrow-in bit from `self`, and returns a tuple of the
1629 /// difference along with a boolean indicating whether an arithmetic
1630 /// overflow would occur. On overflow, the wrapped value is returned.
1632 /// This allows chaining together multiple subtractions to create a
1633 /// wider subtraction, and can be useful for bignum subtraction. This
1634 /// method should only be used for the most significant word; for the
1635 /// less significant words the unsigned method
1636 #[doc = concat!("[`", stringify!($UnsignedT), "::borrowing_sub`]")]
1639 /// The output boolean returned by this method is *not* a borrow flag,
1640 /// and should *not* be subtracted from a more significant word.
1642 /// If the input borrow is false, this method is equivalent to
1643 /// [`overflowing_sub`](Self::overflowing_sub).
1648 /// #![feature(bigint_helper_methods)]
1649 /// // Only the most significant word is signed.
1651 #[doc = concat!("// 6 8 (a = 6 × 2^", stringify!($BITS), " + 8)")]
1652 #[doc = concat!("// - -5 9 (b = -5 × 2^", stringify!($BITS), " + 9)")]
1654 #[doc = concat!("// 10 MAX (diff = 10 × 2^", stringify!($BITS), " + 2^", stringify!($BITS), " - 1)")]
1656 #[doc = concat!("let (a1, a0): (", stringify!($SelfT), ", ", stringify!($UnsignedT), ") = (6, 8);")]
1657 #[doc = concat!("let (b1, b0): (", stringify!($SelfT), ", ", stringify!($UnsignedT), ") = (-5, 9);")]
1658 /// let borrow0 = false;
1660 #[doc = concat!("// ", stringify!($UnsignedT), "::borrowing_sub for the less significant words")]
1661 /// let (diff0, borrow1) = a0.borrowing_sub(b0, borrow0);
1662 /// assert_eq!(borrow1, true);
1664 #[doc = concat!("// ", stringify!($SelfT), "::borrowing_sub for the most significant word")]
1665 /// let (diff1, overflow) = a1.borrowing_sub(b1, borrow1);
1666 /// assert_eq!(overflow, false);
1668 #[doc = concat!("assert_eq!((diff1, diff0), (10, ", stringify!($UnsignedT), "::MAX));")]
1670 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
1671 #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")]
1672 #[must_use = "this returns the result of the operation, \
1673 without modifying the original"]
1675 pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
1676 // note: longer-term this should be done via an intrinsic.
1677 // note: no intermediate overflow is required (https://github.com/rust-lang/rust/issues/85532#issuecomment-1032214946).
1678 let (a, b) = self.overflowing_sub(rhs);
1679 let (c, d) = a.overflowing_sub(borrow as $SelfT);
1683 /// Calculates `self` - `rhs` with an unsigned `rhs`
1685 /// Returns a tuple of the subtraction along with a boolean indicating
1686 /// whether an arithmetic overflow would occur. If an overflow would
1687 /// have occurred then the wrapped value is returned.
1694 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_sub_unsigned(2), (-1, false));")]
1695 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX).overflowing_sub_unsigned(", stringify!($UnsignedT), "::MAX), (", stringify!($SelfT), "::MIN, false));")]
1696 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 2).overflowing_sub_unsigned(3), (", stringify!($SelfT), "::MAX, true));")]
1698 #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
1699 #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
1700 #[must_use = "this returns the result of the operation, \
1701 without modifying the original"]
1703 pub const fn overflowing_sub_unsigned(self, rhs: $UnsignedT) -> (Self, bool) {
1704 let rhs = rhs as Self;
1705 let (res, overflowed) = self.overflowing_sub(rhs);
1706 (res, overflowed ^ (rhs < 0))
1709 /// Calculates the multiplication of `self` and `rhs`.
1711 /// Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1712 /// would occur. If an overflow would have occurred then the wrapped value is returned.
1719 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));")]
1720 /// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
1722 #[stable(feature = "wrapping", since = "1.7.0")]
1723 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1724 #[must_use = "this returns the result of the operation, \
1725 without modifying the original"]
1727 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1728 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1732 /// Calculates the divisor when `self` is divided by `rhs`.
1734 /// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1735 /// occur. If an overflow would occur then self is returned.
1739 /// This function will panic if `rhs` is 0.
1746 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));")]
1747 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT), "::MIN, true));")]
1750 #[stable(feature = "wrapping", since = "1.7.0")]
1751 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1752 #[must_use = "this returns the result of the operation, \
1753 without modifying the original"]
1754 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1755 // Using `&` helps LLVM see that it is the same check made in division.
1756 if unlikely!((self == Self::MIN) & (rhs == -1)) {
1763 /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1765 /// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1766 /// occur. If an overflow would occur then `self` is returned.
1770 /// This function will panic if `rhs` is 0.
1777 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));")]
1778 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euclid(-1), (", stringify!($SelfT), "::MIN, true));")]
1781 #[stable(feature = "euclidean_division", since = "1.38.0")]
1782 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1783 #[must_use = "this returns the result of the operation, \
1784 without modifying the original"]
1785 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1786 // Using `&` helps LLVM see that it is the same check made in division.
1787 if unlikely!((self == Self::MIN) & (rhs == -1)) {
1790 (self.div_euclid(rhs), false)
1794 /// Calculates the remainder when `self` is divided by `rhs`.
1796 /// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1797 /// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1801 /// This function will panic if `rhs` is 0.
1808 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));")]
1809 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));")]
1812 #[stable(feature = "wrapping", since = "1.7.0")]
1813 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1814 #[must_use = "this returns the result of the operation, \
1815 without modifying the original"]
1816 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1817 if unlikely!(rhs == -1) {
1818 (0, self == Self::MIN)
1825 /// Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
1827 /// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1828 /// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1832 /// This function will panic if `rhs` is 0.
1839 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));")]
1840 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem_euclid(-1), (0, true));")]
1842 #[stable(feature = "euclidean_division", since = "1.38.0")]
1843 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1844 #[must_use = "this returns the result of the operation, \
1845 without modifying the original"]
1847 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1848 if unlikely!(rhs == -1) {
1849 (0, self == Self::MIN)
1851 (self.rem_euclid(rhs), false)
1856 /// Negates self, overflowing if this is equal to the minimum value.
1858 /// Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1859 /// happened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the
1860 /// minimum value will be returned again and `true` will be returned for an overflow happening.
1867 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));")]
1868 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT), "::MIN, true));")]
1871 #[stable(feature = "wrapping", since = "1.7.0")]
1872 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1873 #[must_use = "this returns the result of the operation, \
1874 without modifying the original"]
1875 #[allow(unused_attributes)]
1876 pub const fn overflowing_neg(self) -> (Self, bool) {
1877 if unlikely!(self == Self::MIN) {
1884 /// Shifts self left by `rhs` bits.
1886 /// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1887 /// value was larger than or equal to the number of bits. If the shift value is too large, then value is
1888 /// masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1895 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));")]
1896 /// assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));
1898 #[stable(feature = "wrapping", since = "1.7.0")]
1899 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1900 #[must_use = "this returns the result of the operation, \
1901 without modifying the original"]
1903 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1904 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1907 /// Shifts self right by `rhs` bits.
1909 /// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1910 /// value was larger than or equal to the number of bits. If the shift value is too large, then value is
1911 /// masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1918 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));")]
1919 /// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
1921 #[stable(feature = "wrapping", since = "1.7.0")]
1922 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1923 #[must_use = "this returns the result of the operation, \
1924 without modifying the original"]
1926 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1927 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1930 /// Computes the absolute value of `self`.
1932 /// Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1933 /// happened. If self is the minimum value
1934 #[doc = concat!("(e.g., ", stringify!($SelfT), "::MIN for values of type ", stringify!($SelfT), "),")]
1935 /// then the minimum value will be returned again and true will be returned
1936 /// for an overflow happening.
1943 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));")]
1944 #[doc = concat!("assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));")]
1945 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN).overflowing_abs(), (", stringify!($SelfT), "::MIN, true));")]
1947 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1948 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1949 #[must_use = "this returns the result of the operation, \
1950 without modifying the original"]
1952 pub const fn overflowing_abs(self) -> (Self, bool) {
1953 (self.wrapping_abs(), self == Self::MIN)
1956 /// Raises self to the power of `exp`, using exponentiation by squaring.
1958 /// Returns a tuple of the exponentiation along with a bool indicating
1959 /// whether an overflow happened.
1966 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));")]
1967 /// assert_eq!(3i8.overflowing_pow(5), (-13, true));
1969 #[stable(feature = "no_panic_pow", since = "1.34.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 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1978 let mut base = self;
1979 let mut acc: Self = 1;
1980 let mut overflown = false;
1981 // Scratch space for storing results of overflowing_mul.
1986 r = acc.overflowing_mul(base);
1991 r = base.overflowing_mul(base);
1996 // since exp!=0, finally the exp must be 1.
1997 // Deal with the final bit of the exponent separately, since
1998 // squaring the base afterwards is not necessary and may cause a
1999 // needless overflow.
2000 r = acc.overflowing_mul(base);
2005 /// Raises self to the power of `exp`, using exponentiation by squaring.
2012 #[doc = concat!("let x: ", stringify!($SelfT), " = 2; // or any other integer type")]
2014 /// assert_eq!(x.pow(5), 32);
2016 #[stable(feature = "rust1", since = "1.0.0")]
2017 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2018 #[must_use = "this returns the result of the operation, \
2019 without modifying the original"]
2021 #[rustc_inherit_overflow_checks]
2022 pub const fn pow(self, mut exp: u32) -> Self {
2026 let mut base = self;
2037 // since exp!=0, finally the exp must be 1.
2038 // Deal with the final bit of the exponent separately, since
2039 // squaring the base afterwards is not necessary and may cause a
2040 // needless overflow.
2044 /// Calculates the quotient of Euclidean division of `self` by `rhs`.
2046 /// This computes the integer `q` such that `self = q * rhs + r`, with
2047 /// `r = self.rem_euclid(rhs)` and `0 <= r < abs(rhs)`.
2049 /// In other words, the result is `self / rhs` rounded to the integer `q`
2050 /// such that `self >= q * rhs`.
2051 /// If `self > 0`, this is equal to round towards zero (the default in Rust);
2052 /// if `self < 0`, this is equal to round towards +/- infinity.
2056 /// This function will panic if `rhs` is 0 or the division results in overflow.
2063 #[doc = concat!("let a: ", stringify!($SelfT), " = 7; // or any other integer type")]
2066 /// assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
2067 /// assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
2068 /// assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
2069 /// assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
2071 #[stable(feature = "euclidean_division", since = "1.38.0")]
2072 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
2073 #[must_use = "this returns the result of the operation, \
2074 without modifying the original"]
2076 #[rustc_inherit_overflow_checks]
2077 pub const fn div_euclid(self, rhs: Self) -> Self {
2080 return if rhs > 0 { q - 1 } else { q + 1 }
2086 /// Calculates the least nonnegative remainder of `self (mod rhs)`.
2088 /// This is done as if by the Euclidean division algorithm -- given
2089 /// `r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) + r`, and
2090 /// `0 <= r < abs(rhs)`.
2094 /// This function will panic if `rhs` is 0 or the division results in overflow.
2101 #[doc = concat!("let a: ", stringify!($SelfT), " = 7; // or any other integer type")]
2104 /// assert_eq!(a.rem_euclid(b), 3);
2105 /// assert_eq!((-a).rem_euclid(b), 1);
2106 /// assert_eq!(a.rem_euclid(-b), 3);
2107 /// assert_eq!((-a).rem_euclid(-b), 1);
2109 #[stable(feature = "euclidean_division", since = "1.38.0")]
2110 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
2111 #[must_use = "this returns the result of the operation, \
2112 without modifying the original"]
2114 #[rustc_inherit_overflow_checks]
2115 pub const fn rem_euclid(self, rhs: Self) -> Self {
2118 // Semantically equivalent to `if rhs < 0 { r - rhs } else { r + rhs }`.
2119 // If `rhs` is not `Self::MIN`, then `r + abs(rhs)` will not overflow
2120 // and is clearly equivalent, because `r` is negative.
2121 // Otherwise, `rhs` is `Self::MIN`, then we have
2122 // `r.wrapping_add(Self::MIN.wrapping_abs())`, which evaluates
2123 // to `r.wrapping_add(Self::MIN)`, which is equivalent to
2124 // `r - Self::MIN`, which is what we wanted (and will not overflow
2125 // for negative `r`).
2126 r.wrapping_add(rhs.wrapping_abs())
2132 /// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
2136 /// This function will panic if `rhs` is zero.
2138 /// ## Overflow behavior
2140 /// On overflow, this function will panic if overflow checks are enabled (default in debug
2141 /// mode) and wrap if overflow checks are disabled (default in release mode).
2148 /// #![feature(int_roundings)]
2149 #[doc = concat!("let a: ", stringify!($SelfT)," = 8;")]
2152 /// assert_eq!(a.div_floor(b), 2);
2153 /// assert_eq!(a.div_floor(-b), -3);
2154 /// assert_eq!((-a).div_floor(b), -3);
2155 /// assert_eq!((-a).div_floor(-b), 2);
2157 #[unstable(feature = "int_roundings", issue = "88581")]
2158 #[must_use = "this returns the result of the operation, \
2159 without modifying the original"]
2161 #[rustc_inherit_overflow_checks]
2162 pub const fn div_floor(self, rhs: Self) -> Self {
2165 if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) {
2172 /// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
2176 /// This function will panic if `rhs` is zero.
2178 /// ## Overflow behavior
2180 /// On overflow, this function will panic if overflow checks are enabled (default in debug
2181 /// mode) and wrap if overflow checks are disabled (default in release mode).
2188 /// #![feature(int_roundings)]
2189 #[doc = concat!("let a: ", stringify!($SelfT)," = 8;")]
2192 /// assert_eq!(a.div_ceil(b), 3);
2193 /// assert_eq!(a.div_ceil(-b), -2);
2194 /// assert_eq!((-a).div_ceil(b), -2);
2195 /// assert_eq!((-a).div_ceil(-b), 3);
2197 #[unstable(feature = "int_roundings", issue = "88581")]
2198 #[must_use = "this returns the result of the operation, \
2199 without modifying the original"]
2201 #[rustc_inherit_overflow_checks]
2202 pub const fn div_ceil(self, rhs: Self) -> Self {
2205 if (r > 0 && rhs > 0) || (r < 0 && rhs < 0) {
2212 /// If `rhs` is positive, calculates the smallest value greater than or
2213 /// equal to `self` that is a multiple of `rhs`. If `rhs` is negative,
2214 /// calculates the largest value less than or equal to `self` that is a
2215 /// multiple of `rhs`.
2219 /// This function will panic if `rhs` is zero.
2221 /// ## Overflow behavior
2223 /// On overflow, this function will panic if overflow checks are enabled (default in debug
2224 /// mode) and wrap if overflow checks are disabled (default in release mode).
2231 /// #![feature(int_roundings)]
2232 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".next_multiple_of(8), 16);")]
2233 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".next_multiple_of(8), 24);")]
2234 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".next_multiple_of(-8), 16);")]
2235 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".next_multiple_of(-8), 16);")]
2236 #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").next_multiple_of(8), -16);")]
2237 #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").next_multiple_of(8), -16);")]
2238 #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").next_multiple_of(-8), -16);")]
2239 #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").next_multiple_of(-8), -24);")]
2241 #[unstable(feature = "int_roundings", issue = "88581")]
2242 #[must_use = "this returns the result of the operation, \
2243 without modifying the original"]
2245 #[rustc_inherit_overflow_checks]
2246 pub const fn next_multiple_of(self, rhs: Self) -> Self {
2247 // This would otherwise fail when calculating `r` when self == T::MIN.
2253 let m = if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) {
2266 /// If `rhs` is positive, calculates the smallest value greater than or
2267 /// equal to `self` that is a multiple of `rhs`. If `rhs` is negative,
2268 /// calculates the largest value less than or equal to `self` that is a
2269 /// multiple of `rhs`. Returns `None` if `rhs` is zero or the operation
2270 /// would result in overflow.
2277 /// #![feature(int_roundings)]
2278 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(16));")]
2279 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(24));")]
2280 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(-8), Some(16));")]
2281 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(-8), Some(16));")]
2282 #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").checked_next_multiple_of(8), Some(-16));")]
2283 #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").checked_next_multiple_of(8), Some(-16));")]
2284 #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").checked_next_multiple_of(-8), Some(-16));")]
2285 #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").checked_next_multiple_of(-8), Some(-24));")]
2286 #[doc = concat!("assert_eq!(1_", stringify!($SelfT), ".checked_next_multiple_of(0), None);")]
2287 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_multiple_of(2), None);")]
2289 #[unstable(feature = "int_roundings", issue = "88581")]
2290 #[must_use = "this returns the result of the operation, \
2291 without modifying the original"]
2293 pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
2294 // This would otherwise fail when calculating `r` when self == T::MIN.
2299 let r = try_opt!(self.checked_rem(rhs));
2300 let m = if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) {
2301 // r + rhs cannot overflow because they have opposite signs
2310 // rhs - m cannot overflow because m has the same sign as rhs
2311 self.checked_add(rhs - m)
2315 /// Returns the logarithm of the number with respect to an arbitrary base,
2318 /// This method might not be optimized owing to implementation details;
2319 /// `ilog2` can produce results more efficiently for base 2, and `ilog10`
2320 /// can produce results more efficiently for base 10.
2324 /// This function will panic if `self` is less than or equal to zero,
2325 /// or if `base` is less than 2.
2330 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".ilog(5), 1);")]
2332 #[stable(feature = "int_log", since = "1.67.0")]
2333 #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
2334 #[rustc_allow_const_fn_unstable(const_option)]
2335 #[must_use = "this returns the result of the operation, \
2336 without modifying the original"]
2339 pub const fn ilog(self, base: Self) -> u32 {
2340 assert!(base >= 2, "base of integer logarithm must be at least 2");
2341 self.checked_ilog(base).expect("argument of integer logarithm must be positive")
2344 /// Returns the base 2 logarithm of the number, rounded down.
2348 /// This function will panic if `self` is less than or equal to zero.
2353 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".ilog2(), 1);")]
2355 #[stable(feature = "int_log", since = "1.67.0")]
2356 #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
2357 #[rustc_allow_const_fn_unstable(const_option)]
2358 #[must_use = "this returns the result of the operation, \
2359 without modifying the original"]
2362 pub const fn ilog2(self) -> u32 {
2363 self.checked_ilog2().expect("argument of integer logarithm must be positive")
2366 /// Returns the base 10 logarithm of the number, rounded down.
2370 /// This function will panic if `self` is less than or equal to zero.
2375 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".ilog10(), 1);")]
2377 #[stable(feature = "int_log", since = "1.67.0")]
2378 #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
2379 #[rustc_allow_const_fn_unstable(const_option)]
2380 #[must_use = "this returns the result of the operation, \
2381 without modifying the original"]
2384 pub const fn ilog10(self) -> u32 {
2385 self.checked_ilog10().expect("argument of integer logarithm must be positive")
2388 /// Returns the logarithm of the number with respect to an arbitrary base,
2391 /// Returns `None` if the number is negative or zero, or if the base is not at least 2.
2393 /// This method might not be optimized owing to implementation details;
2394 /// `checked_ilog2` can produce results more efficiently for base 2, and
2395 /// `checked_ilog10` can produce results more efficiently for base 10.
2400 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_ilog(5), Some(1));")]
2402 #[stable(feature = "int_log", since = "1.67.0")]
2403 #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
2404 #[must_use = "this returns the result of the operation, \
2405 without modifying the original"]
2407 pub const fn checked_ilog(self, base: Self) -> Option<u32> {
2408 if self <= 0 || base <= 1 {
2414 // Optimization for 128 bit wide integers.
2415 if Self::BITS == 128 {
2416 let b = Self::ilog2(self) / (Self::ilog2(base) + 1);
2418 r /= base.pow(b as u32);
2429 /// Returns the base 2 logarithm of the number, rounded down.
2431 /// Returns `None` if the number is negative or zero.
2436 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_ilog2(), Some(1));")]
2438 #[stable(feature = "int_log", since = "1.67.0")]
2439 #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
2440 #[must_use = "this returns the result of the operation, \
2441 without modifying the original"]
2443 pub const fn checked_ilog2(self) -> Option<u32> {
2447 // SAFETY: We just checked that this number is positive
2448 let log = (Self::BITS - 1) - unsafe { intrinsics::ctlz_nonzero(self) as u32 };
2453 /// Returns the base 10 logarithm of the number, rounded down.
2455 /// Returns `None` if the number is negative or zero.
2460 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_ilog10(), Some(1));")]
2462 #[stable(feature = "int_log", since = "1.67.0")]
2463 #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
2464 #[must_use = "this returns the result of the operation, \
2465 without modifying the original"]
2467 pub const fn checked_ilog10(self) -> Option<u32> {
2469 Some(int_log10::$ActualT(self as $ActualT))
2475 /// Computes the absolute value of `self`.
2477 /// # Overflow behavior
2479 /// The absolute value of
2480 #[doc = concat!("`", stringify!($SelfT), "::MIN`")]
2481 /// cannot be represented as an
2482 #[doc = concat!("`", stringify!($SelfT), "`,")]
2483 /// and attempting to calculate it will cause an overflow. This means
2484 /// that code in debug mode will trigger a panic on this case and
2485 /// optimized code will return
2486 #[doc = concat!("`", stringify!($SelfT), "::MIN`")]
2487 /// without a panic.
2494 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".abs(), 10);")]
2495 #[doc = concat!("assert_eq!((-10", stringify!($SelfT), ").abs(), 10);")]
2497 #[stable(feature = "rust1", since = "1.0.0")]
2498 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2499 #[allow(unused_attributes)]
2500 #[must_use = "this returns the result of the operation, \
2501 without modifying the original"]
2503 #[rustc_inherit_overflow_checks]
2504 pub const fn abs(self) -> Self {
2505 // Note that the #[rustc_inherit_overflow_checks] and #[inline]
2506 // above mean that the overflow semantics of the subtraction
2507 // depend on the crate we're being called from.
2508 if self.is_negative() {
2515 /// Computes the absolute difference between `self` and `other`.
2517 /// This function always returns the correct answer without overflow or
2518 /// panics by returning an unsigned integer.
2525 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(80), 20", stringify!($UnsignedT), ");")]
2526 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(110), 10", stringify!($UnsignedT), ");")]
2527 #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").abs_diff(80), 180", stringify!($UnsignedT), ");")]
2528 #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").abs_diff(-120), 20", stringify!($UnsignedT), ");")]
2529 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.abs_diff(", stringify!($SelfT), "::MAX), ", stringify!($UnsignedT), "::MAX);")]
2531 #[stable(feature = "int_abs_diff", since = "1.60.0")]
2532 #[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
2533 #[must_use = "this returns the result of the operation, \
2534 without modifying the original"]
2536 pub const fn abs_diff(self, other: Self) -> $UnsignedT {
2538 // Converting a non-negative x from signed to unsigned by using
2539 // `x as U` is left unchanged, but a negative x is converted
2540 // to value x + 2^N. Thus if `s` and `o` are binary variables
2541 // respectively indicating whether `self` and `other` are
2542 // negative, we are computing the mathematical value:
2544 // (other + o*2^N) - (self + s*2^N) mod 2^N
2545 // other - self + (o-s)*2^N mod 2^N
2546 // other - self mod 2^N
2548 // Finally, taking the mod 2^N of the mathematical value of
2549 // `other - self` does not change it as it already is
2550 // in the range [0, 2^N).
2551 (other as $UnsignedT).wrapping_sub(self as $UnsignedT)
2553 (self as $UnsignedT).wrapping_sub(other as $UnsignedT)
2557 /// Returns a number representing sign of `self`.
2559 /// - `0` if the number is zero
2560 /// - `1` if the number is positive
2561 /// - `-1` if the number is negative
2568 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".signum(), 1);")]
2569 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".signum(), 0);")]
2570 #[doc = concat!("assert_eq!((-10", stringify!($SelfT), ").signum(), -1);")]
2572 #[stable(feature = "rust1", since = "1.0.0")]
2573 #[rustc_const_stable(feature = "const_int_sign", since = "1.47.0")]
2574 #[must_use = "this returns the result of the operation, \
2575 without modifying the original"]
2577 #[rustc_allow_const_fn_unstable(const_cmp)]
2578 pub const fn signum(self) -> Self {
2579 // Picking the right way to phrase this is complicated
2580 // (<https://graphics.stanford.edu/~seander/bithacks.html#CopyIntegerSign>)
2581 // so delegate it to `Ord` which is already producing -1/0/+1
2582 // exactly like we need and can be the place to deal with the complexity.
2586 /// Returns `true` if `self` is positive and `false` if the number is zero or
2594 #[doc = concat!("assert!(10", stringify!($SelfT), ".is_positive());")]
2595 #[doc = concat!("assert!(!(-10", stringify!($SelfT), ").is_positive());")]
2598 #[stable(feature = "rust1", since = "1.0.0")]
2599 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2601 pub const fn is_positive(self) -> bool { self > 0 }
2603 /// Returns `true` if `self` is negative and `false` if the number is zero or
2611 #[doc = concat!("assert!((-10", stringify!($SelfT), ").is_negative());")]
2612 #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_negative());")]
2615 #[stable(feature = "rust1", since = "1.0.0")]
2616 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2618 pub const fn is_negative(self) -> bool { self < 0 }
2620 /// Return the memory representation of this integer as a byte array in
2621 /// big-endian (network) byte order.
2623 #[doc = $to_xe_bytes_doc]
2628 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();")]
2629 #[doc = concat!("assert_eq!(bytes, ", $be_bytes, ");")]
2631 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2632 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2633 #[must_use = "this returns the result of the operation, \
2634 without modifying the original"]
2636 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2637 self.to_be().to_ne_bytes()
2640 /// Return the memory representation of this integer as a byte array in
2641 /// little-endian byte order.
2643 #[doc = $to_xe_bytes_doc]
2648 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();")]
2649 #[doc = concat!("assert_eq!(bytes, ", $le_bytes, ");")]
2651 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2652 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2653 #[must_use = "this returns the result of the operation, \
2654 without modifying the original"]
2656 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2657 self.to_le().to_ne_bytes()
2660 /// Return the memory representation of this integer as a byte array in
2661 /// native byte order.
2663 /// As the target platform's native endianness is used, portable code
2664 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2667 #[doc = $to_xe_bytes_doc]
2669 /// [`to_be_bytes`]: Self::to_be_bytes
2670 /// [`to_le_bytes`]: Self::to_le_bytes
2675 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();")]
2678 /// if cfg!(target_endian = "big") {
2679 #[doc = concat!(" ", $be_bytes)]
2681 #[doc = concat!(" ", $le_bytes)]
2685 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2686 #[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 them to arrays of bytes
2689 #[must_use = "this returns the result of the operation, \
2690 without modifying the original"]
2692 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2693 // SAFETY: integers are plain old datatypes so we can always transmute them to
2695 unsafe { mem::transmute(self) }
2698 /// Create an integer value from its representation as a byte array in
2701 #[doc = $from_xe_bytes_doc]
2706 #[doc = concat!("let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");")]
2707 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2710 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2713 #[doc = concat!("fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2714 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2716 #[doc = concat!(" ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())")]
2719 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2720 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2723 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2724 Self::from_be(Self::from_ne_bytes(bytes))
2727 /// Create an integer value from its representation as a byte array in
2730 #[doc = $from_xe_bytes_doc]
2735 #[doc = concat!("let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");")]
2736 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2739 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2742 #[doc = concat!("fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2743 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2745 #[doc = concat!(" ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())")]
2748 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2749 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2752 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2753 Self::from_le(Self::from_ne_bytes(bytes))
2756 /// Create an integer value from its memory representation as a byte
2757 /// array in native endianness.
2759 /// As the target platform's native endianness is used, portable code
2760 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2761 /// appropriate instead.
2763 /// [`from_be_bytes`]: Self::from_be_bytes
2764 /// [`from_le_bytes`]: Self::from_le_bytes
2766 #[doc = $from_xe_bytes_doc]
2771 #[doc = concat!("let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {")]
2772 #[doc = concat!(" ", $be_bytes)]
2774 #[doc = concat!(" ", $le_bytes)]
2776 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2779 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2782 #[doc = concat!("fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2783 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2785 #[doc = concat!(" ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())")]
2788 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2789 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2791 // SAFETY: const sound because integers are plain old datatypes so we can always
2792 // transmute to them
2794 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2795 // SAFETY: integers are plain old datatypes so we can always transmute to them
2796 unsafe { mem::transmute(bytes) }
2799 /// New code should prefer to use
2800 #[doc = concat!("[`", stringify!($SelfT), "::MIN", "`] instead.")]
2802 /// Returns the smallest value that can be represented by this integer type.
2803 #[stable(feature = "rust1", since = "1.0.0")]
2806 #[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
2807 #[deprecated(since = "TBD", note = "replaced by the `MIN` associated constant on this type")]
2808 pub const fn min_value() -> Self {
2812 /// New code should prefer to use
2813 #[doc = concat!("[`", stringify!($SelfT), "::MAX", "`] instead.")]
2815 /// Returns the largest value that can be represented by this integer type.
2816 #[stable(feature = "rust1", since = "1.0.0")]
2819 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2820 #[deprecated(since = "TBD", note = "replaced by the `MAX` associated constant on this type")]
2821 pub const fn max_value() -> Self {