1 macro_rules
! int_impl
{
2 ($SelfT
:ty
, $ActualT
:ident
, $UnsignedT
:ty
, $BITS
:expr
, $BITS_MINUS_ONE
:expr
, $Min
:expr
, $Max
:expr
,
3 $rot
:expr
, $rot_op
:expr
, $rot_result
:expr
, $swap_op
:expr
, $swapped
:expr
,
4 $reversed
:expr
, $le_bytes
:expr
, $be_bytes
:expr
,
5 $to_xe_bytes_doc
:expr
, $from_xe_bytes_doc
:expr
) => {
6 /// The smallest value that can be represented by this integer type,
7 #[doc = concat!("−2<sup>", $BITS_MINUS_ONE, "</sup>.")]
14 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN, ", stringify!($Min), ");")]
16 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
17 pub const MIN
: Self = !0 ^
((!0 as $UnsignedT
) >> 1) as Self;
19 /// The largest value that can be represented by this integer type,
20 #[doc = concat!("2<sup>", $BITS_MINUS_ONE, "</sup> − 1.")]
27 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($Max), ");")]
29 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
30 pub const MAX
: Self = !Self::MIN
;
32 /// The size of this integer type in bits.
37 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::BITS, ", stringify!($BITS), ");")]
39 #[stable(feature = "int_bits_const", since = "1.53.0")]
40 pub const BITS
: u32 = $BITS
;
42 /// Converts a string slice in a given base to an integer.
44 /// The string is expected to be an optional `+` or `-` sign followed by digits.
45 /// Leading and trailing whitespace represent an error. Digits are a subset of these characters,
46 /// depending on `radix`:
54 /// This function panics if `radix` is not in the range from 2 to 36.
61 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));")]
63 #[stable(feature = "rust1", since = "1.0.0")]
64 pub fn from_str_radix(src
: &str, radix
: u32) -> Result
<Self, ParseIntError
> {
65 from_str_radix(src
, radix
)
68 /// Returns the number of ones in the binary representation of `self`.
75 #[doc = concat!("let n = 0b100_0000", stringify!($SelfT), ";")]
77 /// assert_eq!(n.count_ones(), 1);
80 #[stable(feature = "rust1", since = "1.0.0")]
81 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
82 #[doc(alias = "popcount")]
83 #[doc(alias = "popcnt")]
84 #[must_use = "this returns the result of the operation, \
85 without modifying the original"]
87 pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
89 /// Returns the number of zeros in the binary representation of `self`.
96 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.count_zeros(), 1);")]
98 #[stable(feature = "rust1", since = "1.0.0")]
99 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
100 #[must_use = "this returns the result of the operation, \
101 without modifying the original"]
103 pub const fn count_zeros(self) -> u32 {
107 /// Returns the number of leading zeros in the binary representation of `self`.
114 #[doc = concat!("let n = -1", stringify!($SelfT), ";")]
116 /// assert_eq!(n.leading_zeros(), 0);
118 #[stable(feature = "rust1", since = "1.0.0")]
119 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
120 #[must_use = "this returns the result of the operation, \
121 without modifying the original"]
123 pub const fn leading_zeros(self) -> u32 {
124 (self as $UnsignedT
).leading_zeros()
127 /// Returns the number of trailing zeros in the binary representation of `self`.
134 #[doc = concat!("let n = -4", stringify!($SelfT), ";")]
136 /// assert_eq!(n.trailing_zeros(), 2);
138 #[stable(feature = "rust1", since = "1.0.0")]
139 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
140 #[must_use = "this returns the result of the operation, \
141 without modifying the original"]
143 pub const fn trailing_zeros(self) -> u32 {
144 (self as $UnsignedT
).trailing_zeros()
147 /// Returns the number of leading ones in the binary representation of `self`.
154 #[doc = concat!("let n = -1", stringify!($SelfT), ";")]
156 #[doc = concat!("assert_eq!(n.leading_ones(), ", stringify!($BITS), ");")]
158 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
159 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
160 #[must_use = "this returns the result of the operation, \
161 without modifying the original"]
163 pub const fn leading_ones(self) -> u32 {
164 (self as $UnsignedT
).leading_ones()
167 /// Returns the number of trailing ones in the binary representation of `self`.
174 #[doc = concat!("let n = 3", stringify!($SelfT), ";")]
176 /// assert_eq!(n.trailing_ones(), 2);
178 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
179 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
180 #[must_use = "this returns the result of the operation, \
181 without modifying the original"]
183 pub const fn trailing_ones(self) -> u32 {
184 (self as $UnsignedT
).trailing_ones()
187 /// Shifts the bits to the left by a specified amount, `n`,
188 /// wrapping the truncated bits to the end of the resulting integer.
190 /// Please note this isn't the same operation as the `<<` shifting operator!
197 #[doc = concat!("let n = ", $rot_op, stringify!($SelfT), ";")]
198 #[doc = concat!("let m = ", $rot_result, ";")]
200 #[doc = concat!("assert_eq!(n.rotate_left(", $rot, "), m);")]
202 #[stable(feature = "rust1", since = "1.0.0")]
203 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
204 #[must_use = "this returns the result of the operation, \
205 without modifying the original"]
207 pub const fn rotate_left(self, n
: u32) -> Self {
208 (self as $UnsignedT
).rotate_left(n
) as Self
211 /// Shifts the bits to the right by a specified amount, `n`,
212 /// wrapping the truncated bits to the beginning of the resulting
215 /// Please note this isn't the same operation as the `>>` shifting operator!
222 #[doc = concat!("let n = ", $rot_result, stringify!($SelfT), ";")]
223 #[doc = concat!("let m = ", $rot_op, ";")]
225 #[doc = concat!("assert_eq!(n.rotate_right(", $rot, "), m);")]
227 #[stable(feature = "rust1", since = "1.0.0")]
228 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
229 #[must_use = "this returns the result of the operation, \
230 without modifying the original"]
232 pub const fn rotate_right(self, n
: u32) -> Self {
233 (self as $UnsignedT
).rotate_right(n
) as Self
236 /// Reverses the byte order of the integer.
243 #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
245 /// let m = n.swap_bytes();
247 #[doc = concat!("assert_eq!(m, ", $swapped, ");")]
249 #[stable(feature = "rust1", since = "1.0.0")]
250 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
251 #[must_use = "this returns the result of the operation, \
252 without modifying the original"]
254 pub const fn swap_bytes(self) -> Self {
255 (self as $UnsignedT
).swap_bytes() as Self
258 /// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
259 /// second least-significant bit becomes second most-significant bit, etc.
266 #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
267 /// let m = n.reverse_bits();
269 #[doc = concat!("assert_eq!(m, ", $reversed, ");")]
270 #[doc = concat!("assert_eq!(0, 0", stringify!($SelfT), ".reverse_bits());")]
272 #[stable(feature = "reverse_bits", since = "1.37.0")]
273 #[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
274 #[must_use = "this returns the result of the operation, \
275 without modifying the original"]
277 pub const fn reverse_bits(self) -> Self {
278 (self as $UnsignedT
).reverse_bits() as Self
281 /// Converts an integer from big endian to the target's endianness.
283 /// On big endian this is a no-op. On little endian the bytes are swapped.
290 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
292 /// if cfg!(target_endian = "big") {
293 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_be(n), n)")]
295 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())")]
298 #[stable(feature = "rust1", since = "1.0.0")]
299 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
302 pub const fn from_be(x
: Self) -> Self {
303 #[cfg(target_endian = "big")]
307 #[cfg(not(target_endian = "big"))]
313 /// Converts an integer from little endian to the target's endianness.
315 /// On little endian this is a no-op. On big endian the bytes are swapped.
322 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
324 /// if cfg!(target_endian = "little") {
325 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_le(n), n)")]
327 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())")]
330 #[stable(feature = "rust1", since = "1.0.0")]
331 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
334 pub const fn from_le(x
: Self) -> Self {
335 #[cfg(target_endian = "little")]
339 #[cfg(not(target_endian = "little"))]
345 /// Converts `self` to big endian from the target's endianness.
347 /// On big endian this is a no-op. On little endian the bytes are swapped.
354 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
356 /// if cfg!(target_endian = "big") {
357 /// assert_eq!(n.to_be(), n)
359 /// assert_eq!(n.to_be(), n.swap_bytes())
362 #[stable(feature = "rust1", since = "1.0.0")]
363 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
364 #[must_use = "this returns the result of the operation, \
365 without modifying the original"]
367 pub const fn to_be(self) -> Self { // or not to be?
368 #[cfg(target_endian = "big")]
372 #[cfg(not(target_endian = "big"))]
378 /// Converts `self` to little endian from the target's endianness.
380 /// On little endian this is a no-op. On big endian the bytes are swapped.
387 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
389 /// if cfg!(target_endian = "little") {
390 /// assert_eq!(n.to_le(), n)
392 /// assert_eq!(n.to_le(), n.swap_bytes())
395 #[stable(feature = "rust1", since = "1.0.0")]
396 #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
397 #[must_use = "this returns the result of the operation, \
398 without modifying the original"]
400 pub const fn to_le(self) -> Self {
401 #[cfg(target_endian = "little")]
405 #[cfg(not(target_endian = "little"))]
411 /// Checked integer addition. Computes `self + rhs`, returning `None`
412 /// if overflow occurred.
419 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(1), Some(", stringify!($SelfT), "::MAX - 1));")]
420 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);")]
422 #[stable(feature = "rust1", since = "1.0.0")]
423 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
424 #[must_use = "this returns the result of the operation, \
425 without modifying the original"]
427 pub const fn checked_add(self, rhs
: Self) -> Option
<Self> {
428 let (a
, b
) = self.overflowing_add(rhs
);
429 if unlikely
!(b
) {None}
else {Some(a)}
432 /// Unchecked integer addition. Computes `self + rhs`, assuming overflow
437 /// This results in undefined behavior when
438 #[doc = concat!("`self + rhs > ", stringify!($SelfT), "::MAX` or `self + rhs < ", stringify!($SelfT), "::MIN`,")]
439 /// i.e. when [`checked_add`] would return `None`.
441 #[doc = concat!("[`checked_add`]: ", stringify!($SelfT), "::checked_add")]
443 feature
= "unchecked_math",
444 reason
= "niche optimization path",
447 #[must_use = "this returns the result of the operation, \
448 without modifying the original"]
449 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
451 pub const unsafe fn unchecked_add(self, rhs
: Self) -> Self {
452 // SAFETY: the caller must uphold the safety contract for
454 unsafe { intrinsics::unchecked_add(self, rhs) }
457 /// Checked addition with an unsigned integer. Computes `self + rhs`,
458 /// returning `None` if overflow occurred.
465 /// # #![feature(mixed_integer_ops)]
466 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_add_unsigned(2), Some(3));")]
467 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add_unsigned(3), None);")]
469 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
470 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
471 #[must_use = "this returns the result of the operation, \
472 without modifying the original"]
474 pub const fn checked_add_unsigned(self, rhs
: $UnsignedT
) -> Option
<Self> {
475 let (a
, b
) = self.overflowing_add_unsigned(rhs
);
476 if unlikely
!(b
) {None}
else {Some(a)}
479 /// Checked integer subtraction. Computes `self - rhs`, returning `None` if
480 /// overflow occurred.
487 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 2).checked_sub(1), Some(", stringify!($SelfT), "::MIN + 1));")]
488 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 2).checked_sub(3), None);")]
490 #[stable(feature = "rust1", since = "1.0.0")]
491 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
492 #[must_use = "this returns the result of the operation, \
493 without modifying the original"]
495 pub const fn checked_sub(self, rhs
: Self) -> Option
<Self> {
496 let (a
, b
) = self.overflowing_sub(rhs
);
497 if unlikely
!(b
) {None}
else {Some(a)}
500 /// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
505 /// This results in undefined behavior when
506 #[doc = concat!("`self - rhs > ", stringify!($SelfT), "::MAX` or `self - rhs < ", stringify!($SelfT), "::MIN`,")]
507 /// i.e. when [`checked_sub`] would return `None`.
509 #[doc = concat!("[`checked_sub`]: ", stringify!($SelfT), "::checked_sub")]
511 feature
= "unchecked_math",
512 reason
= "niche optimization path",
515 #[must_use = "this returns the result of the operation, \
516 without modifying the original"]
517 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
519 pub const unsafe fn unchecked_sub(self, rhs
: Self) -> Self {
520 // SAFETY: the caller must uphold the safety contract for
522 unsafe { intrinsics::unchecked_sub(self, rhs) }
525 /// Checked subtraction with an unsigned integer. Computes `self - rhs`,
526 /// returning `None` if overflow occurred.
533 /// # #![feature(mixed_integer_ops)]
534 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_sub_unsigned(2), Some(-1));")]
535 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 2).checked_sub_unsigned(3), None);")]
537 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
538 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
539 #[must_use = "this returns the result of the operation, \
540 without modifying the original"]
542 pub const fn checked_sub_unsigned(self, rhs
: $UnsignedT
) -> Option
<Self> {
543 let (a
, b
) = self.overflowing_sub_unsigned(rhs
);
544 if unlikely
!(b
) {None}
else {Some(a)}
547 /// Checked integer multiplication. Computes `self * rhs`, returning `None` if
548 /// overflow occurred.
555 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(1), Some(", stringify!($SelfT), "::MAX));")]
556 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);")]
558 #[stable(feature = "rust1", since = "1.0.0")]
559 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
560 #[must_use = "this returns the result of the operation, \
561 without modifying the original"]
563 pub const fn checked_mul(self, rhs
: Self) -> Option
<Self> {
564 let (a
, b
) = self.overflowing_mul(rhs
);
565 if unlikely
!(b
) {None}
else {Some(a)}
568 /// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
573 /// This results in undefined behavior when
574 #[doc = concat!("`self * rhs > ", stringify!($SelfT), "::MAX` or `self * rhs < ", stringify!($SelfT), "::MIN`,")]
575 /// i.e. when [`checked_mul`] would return `None`.
577 #[doc = concat!("[`checked_mul`]: ", stringify!($SelfT), "::checked_mul")]
579 feature
= "unchecked_math",
580 reason
= "niche optimization path",
583 #[must_use = "this returns the result of the operation, \
584 without modifying the original"]
585 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
587 pub const unsafe fn unchecked_mul(self, rhs
: Self) -> Self {
588 // SAFETY: the caller must uphold the safety contract for
590 unsafe { intrinsics::unchecked_mul(self, rhs) }
593 /// Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
594 /// or the division results in overflow.
601 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 1).checked_div(-1), Some(", stringify!($Max), "));")]
602 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_div(-1), None);")]
603 #[doc = concat!("assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);")]
605 #[stable(feature = "rust1", since = "1.0.0")]
606 #[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
607 #[must_use = "this returns the result of the operation, \
608 without modifying the original"]
610 pub const fn checked_div(self, rhs
: Self) -> Option
<Self> {
611 if unlikely
!(rhs
== 0 || ((self == Self::MIN
) && (rhs
== -1))) {
614 // SAFETY: div by zero and by INT_MIN have been checked above
615 Some(unsafe { intrinsics::unchecked_div(self, rhs) }
)
619 /// Checked Euclidean division. Computes `self.div_euclid(rhs)`,
620 /// returning `None` if `rhs == 0` or the division results in overflow.
627 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 1).checked_div_euclid(-1), Some(", stringify!($Max), "));")]
628 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_div_euclid(-1), None);")]
629 #[doc = concat!("assert_eq!((1", stringify!($SelfT), ").checked_div_euclid(0), None);")]
631 #[stable(feature = "euclidean_division", since = "1.38.0")]
632 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
633 #[must_use = "this returns the result of the operation, \
634 without modifying the original"]
636 pub const fn checked_div_euclid(self, rhs
: Self) -> Option
<Self> {
637 // Using `&` helps LLVM see that it is the same check made in division.
638 if unlikely
!(rhs
== 0 || ((self == Self::MIN
) & (rhs
== -1))) {
641 Some(self.div_euclid(rhs
))
645 /// Checked integer remainder. Computes `self % rhs`, returning `None` if
646 /// `rhs == 0` or the division results in overflow.
654 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));")]
655 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);")]
656 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);")]
658 #[stable(feature = "wrapping", since = "1.7.0")]
659 #[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
660 #[must_use = "this returns the result of the operation, \
661 without modifying the original"]
663 pub const fn checked_rem(self, rhs
: Self) -> Option
<Self> {
664 if unlikely
!(rhs
== 0 || ((self == Self::MIN
) && (rhs
== -1))) {
667 // SAFETY: div by zero and by INT_MIN have been checked above
668 Some(unsafe { intrinsics::unchecked_rem(self, rhs) }
)
672 /// Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`
673 /// if `rhs == 0` or the division results in overflow.
680 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));")]
681 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);")]
682 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_rem_euclid(-1), None);")]
684 #[stable(feature = "euclidean_division", since = "1.38.0")]
685 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
686 #[must_use = "this returns the result of the operation, \
687 without modifying the original"]
689 pub const fn checked_rem_euclid(self, rhs
: Self) -> Option
<Self> {
690 // Using `&` helps LLVM see that it is the same check made in division.
691 if unlikely
!(rhs
== 0 || ((self == Self::MIN
) & (rhs
== -1))) {
694 Some(self.rem_euclid(rhs
))
698 /// Checked negation. Computes `-self`, returning `None` if `self == MIN`.
706 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));")]
707 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);")]
709 #[stable(feature = "wrapping", since = "1.7.0")]
710 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
711 #[must_use = "this returns the result of the operation, \
712 without modifying the original"]
714 pub const fn checked_neg(self) -> Option
<Self> {
715 let (a
, b
) = self.overflowing_neg();
716 if unlikely
!(b
) {None}
else {Some(a)}
719 /// Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
720 /// than or equal to the number of bits in `self`.
727 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));")]
728 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);")]
730 #[stable(feature = "wrapping", since = "1.7.0")]
731 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
732 #[must_use = "this returns the result of the operation, \
733 without modifying the original"]
735 pub const fn checked_shl(self, rhs
: u32) -> Option
<Self> {
736 let (a
, b
) = self.overflowing_shl(rhs
);
737 if unlikely
!(b
) {None}
else {Some(a)}
740 /// Unchecked shift left. Computes `self << rhs`, assuming that
741 /// `rhs` is less than the number of bits in `self`.
745 /// This results in undefined behavior if `rhs` is larger than
746 /// or equal to the number of bits in `self`,
747 /// i.e. when [`checked_shl`] would return `None`.
749 #[doc = concat!("[`checked_shl`]: ", stringify!($SelfT), "::checked_shl")]
751 feature
= "unchecked_math",
752 reason
= "niche optimization path",
755 #[must_use = "this returns the result of the operation, \
756 without modifying the original"]
757 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
759 pub const unsafe fn unchecked_shl(self, rhs
: Self) -> Self {
760 // SAFETY: the caller must uphold the safety contract for
762 unsafe { intrinsics::unchecked_shl(self, rhs) }
765 /// Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
766 /// larger than or equal to the number of bits in `self`.
773 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));")]
774 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);")]
776 #[stable(feature = "wrapping", since = "1.7.0")]
777 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
778 #[must_use = "this returns the result of the operation, \
779 without modifying the original"]
781 pub const fn checked_shr(self, rhs
: u32) -> Option
<Self> {
782 let (a
, b
) = self.overflowing_shr(rhs
);
783 if unlikely
!(b
) {None}
else {Some(a)}
786 /// Unchecked shift right. Computes `self >> rhs`, assuming that
787 /// `rhs` is less than the number of bits in `self`.
791 /// This results in undefined behavior if `rhs` is larger than
792 /// or equal to the number of bits in `self`,
793 /// i.e. when [`checked_shr`] would return `None`.
795 #[doc = concat!("[`checked_shr`]: ", stringify!($SelfT), "::checked_shr")]
797 feature
= "unchecked_math",
798 reason
= "niche optimization path",
801 #[must_use = "this returns the result of the operation, \
802 without modifying the original"]
803 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
805 pub const unsafe fn unchecked_shr(self, rhs
: Self) -> Self {
806 // SAFETY: the caller must uphold the safety contract for
808 unsafe { intrinsics::unchecked_shr(self, rhs) }
811 /// Checked absolute value. Computes `self.abs()`, returning `None` if
820 #[doc = concat!("assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));")]
821 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);")]
823 #[stable(feature = "no_panic_abs", since = "1.13.0")]
824 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
825 #[must_use = "this returns the result of the operation, \
826 without modifying the original"]
828 pub const fn checked_abs(self) -> Option
<Self> {
829 if self.is_negative() {
836 /// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
837 /// overflow occurred.
844 #[doc = concat!("assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));")]
845 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);")]
848 #[stable(feature = "no_panic_pow", since = "1.34.0")]
849 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
850 #[must_use = "this returns the result of the operation, \
851 without modifying the original"]
853 pub const fn checked_pow(self, mut exp
: u32) -> Option
<Self> {
858 let mut acc
: Self = 1;
862 acc
= try_opt
!(acc
.checked_mul(base
));
865 base
= try_opt
!(base
.checked_mul(base
));
867 // since exp!=0, finally the exp must be 1.
868 // Deal with the final bit of the exponent separately, since
869 // squaring the base afterwards is not necessary and may cause a
870 // needless overflow.
871 Some(try_opt
!(acc
.checked_mul(base
)))
874 /// Saturating integer addition. Computes `self + rhs`, saturating at the numeric
875 /// bounds instead of overflowing.
882 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);")]
883 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(100), ", stringify!($SelfT), "::MAX);")]
884 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_add(-1), ", stringify!($SelfT), "::MIN);")]
887 #[stable(feature = "rust1", since = "1.0.0")]
888 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
889 #[must_use = "this returns the result of the operation, \
890 without modifying the original"]
892 pub const fn saturating_add(self, rhs
: Self) -> Self {
893 intrinsics
::saturating_add(self, rhs
)
896 /// Saturating addition with an unsigned integer. Computes `self + rhs`,
897 /// saturating at the numeric bounds instead of overflowing.
904 /// # #![feature(mixed_integer_ops)]
905 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_unsigned(2), 3);")]
906 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add_unsigned(100), ", stringify!($SelfT), "::MAX);")]
908 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
909 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
910 #[must_use = "this returns the result of the operation, \
911 without modifying the original"]
913 pub const fn saturating_add_unsigned(self, rhs
: $UnsignedT
) -> Self {
914 // Overflow can only happen at the upper bound
915 // We cannot use `unwrap_or` here because it is not `const`
916 match self.checked_add_unsigned(rhs
) {
922 /// Saturating integer subtraction. Computes `self - rhs`, saturating at the
923 /// numeric bounds instead of overflowing.
930 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);")]
931 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_sub(100), ", stringify!($SelfT), "::MIN);")]
932 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_sub(-1), ", stringify!($SelfT), "::MAX);")]
934 #[stable(feature = "rust1", since = "1.0.0")]
935 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
936 #[must_use = "this returns the result of the operation, \
937 without modifying the original"]
939 pub const fn saturating_sub(self, rhs
: Self) -> Self {
940 intrinsics
::saturating_sub(self, rhs
)
943 /// Saturating subtraction with an unsigned integer. Computes `self - rhs`,
944 /// saturating at the numeric bounds instead of overflowing.
951 /// # #![feature(mixed_integer_ops)]
952 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_sub_unsigned(127), -27);")]
953 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_sub_unsigned(100), ", stringify!($SelfT), "::MIN);")]
955 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
956 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
957 #[must_use = "this returns the result of the operation, \
958 without modifying the original"]
960 pub const fn saturating_sub_unsigned(self, rhs
: $UnsignedT
) -> Self {
961 // Overflow can only happen at the lower bound
962 // We cannot use `unwrap_or` here because it is not `const`
963 match self.checked_sub_unsigned(rhs
) {
969 /// Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
970 /// instead of overflowing.
977 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_neg(), -100);")]
978 #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").saturating_neg(), 100);")]
979 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_neg(), ", stringify!($SelfT), "::MAX);")]
980 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_neg(), ", stringify!($SelfT), "::MIN + 1);")]
983 #[stable(feature = "saturating_neg", since = "1.45.0")]
984 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
985 #[must_use = "this returns the result of the operation, \
986 without modifying the original"]
988 pub const fn saturating_neg(self) -> Self {
989 intrinsics
::saturating_sub(0, self)
992 /// Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
993 /// MIN` instead of overflowing.
1000 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_abs(), 100);")]
1001 #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").saturating_abs(), 100);")]
1002 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_abs(), ", stringify!($SelfT), "::MAX);")]
1003 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 1).saturating_abs(), ", stringify!($SelfT), "::MAX);")]
1006 #[stable(feature = "saturating_neg", since = "1.45.0")]
1007 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1008 #[must_use = "this returns the result of the operation, \
1009 without modifying the original"]
1011 pub const fn saturating_abs(self) -> Self {
1012 if self.is_negative() {
1013 self.saturating_neg()
1019 /// Saturating integer multiplication. Computes `self * rhs`, saturating at the
1020 /// numeric bounds instead of overflowing.
1028 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);")]
1029 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);")]
1030 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);")]
1032 #[stable(feature = "wrapping", since = "1.7.0")]
1033 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1034 #[must_use = "this returns the result of the operation, \
1035 without modifying the original"]
1037 pub const fn saturating_mul(self, rhs
: Self) -> Self {
1038 match self.checked_mul(rhs
) {
1040 None
=> if (self < 0) == (rhs
< 0) {
1048 /// Saturating integer division. Computes `self / rhs`, saturating at the
1049 /// numeric bounds instead of overflowing.
1056 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".saturating_div(2), 2);")]
1057 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_div(-1), ", stringify!($SelfT), "::MIN + 1);")]
1058 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_div(-1), ", stringify!($SelfT), "::MAX);")]
1063 #[doc = concat!("let _ = 1", stringify!($SelfT), ".saturating_div(0);")]
1066 #[stable(feature = "saturating_div", since = "1.58.0")]
1067 #[rustc_const_stable(feature = "saturating_div", since = "1.58.0")]
1068 #[must_use = "this returns the result of the operation, \
1069 without modifying the original"]
1071 pub const fn saturating_div(self, rhs
: Self) -> Self {
1072 match self.overflowing_div(rhs
) {
1073 (result
, false) => result
,
1074 (_result
, true) => Self::MAX
, // MIN / -1 is the only possible saturating overflow
1078 /// Saturating integer exponentiation. Computes `self.pow(exp)`,
1079 /// saturating at the numeric bounds instead of overflowing.
1087 #[doc = concat!("assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);")]
1088 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);")]
1089 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);")]
1091 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1092 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1093 #[must_use = "this returns the result of the operation, \
1094 without modifying the original"]
1096 pub const fn saturating_pow(self, exp
: u32) -> Self {
1097 match self.checked_pow(exp
) {
1099 None
if self < 0 && exp
% 2 == 1 => Self::MIN
,
1104 /// Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
1105 /// boundary of the type.
1112 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);")]
1113 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_add(2), ", stringify!($SelfT), "::MIN + 1);")]
1115 #[stable(feature = "rust1", since = "1.0.0")]
1116 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1117 #[must_use = "this returns the result of the operation, \
1118 without modifying the original"]
1120 pub const fn wrapping_add(self, rhs
: Self) -> Self {
1121 intrinsics
::wrapping_add(self, rhs
)
1124 /// Wrapping (modular) addition with an unsigned integer. Computes
1125 /// `self + rhs`, wrapping around at the boundary of the type.
1132 /// # #![feature(mixed_integer_ops)]
1133 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_add_unsigned(27), 127);")]
1134 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_add_unsigned(2), ", stringify!($SelfT), "::MIN + 1);")]
1136 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1137 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1138 #[must_use = "this returns the result of the operation, \
1139 without modifying the original"]
1141 pub const fn wrapping_add_unsigned(self, rhs
: $UnsignedT
) -> Self {
1142 self.wrapping_add(rhs
as Self)
1145 /// Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1146 /// boundary of the type.
1153 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);")]
1154 #[doc = concat!("assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::MAX), ", stringify!($SelfT), "::MAX);")]
1156 #[stable(feature = "rust1", since = "1.0.0")]
1157 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1158 #[must_use = "this returns the result of the operation, \
1159 without modifying the original"]
1161 pub const fn wrapping_sub(self, rhs
: Self) -> Self {
1162 intrinsics
::wrapping_sub(self, rhs
)
1165 /// Wrapping (modular) subtraction with an unsigned integer. Computes
1166 /// `self - rhs`, wrapping around at the boundary of the type.
1173 /// # #![feature(mixed_integer_ops)]
1174 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".wrapping_sub_unsigned(127), -127);")]
1175 #[doc = concat!("assert_eq!((-2", stringify!($SelfT), ").wrapping_sub_unsigned(", stringify!($UnsignedT), "::MAX), -1);")]
1177 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1178 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1179 #[must_use = "this returns the result of the operation, \
1180 without modifying the original"]
1182 pub const fn wrapping_sub_unsigned(self, rhs
: $UnsignedT
) -> Self {
1183 self.wrapping_sub(rhs
as Self)
1186 /// Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1187 /// the boundary of the type.
1194 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);")]
1195 /// assert_eq!(11i8.wrapping_mul(12), -124);
1197 #[stable(feature = "rust1", since = "1.0.0")]
1198 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1199 #[must_use = "this returns the result of the operation, \
1200 without modifying the original"]
1202 pub const fn wrapping_mul(self, rhs
: Self) -> Self {
1203 intrinsics
::wrapping_mul(self, rhs
)
1206 /// Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1207 /// boundary of the type.
1209 /// The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1210 /// `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1211 /// that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1215 /// This function will panic if `rhs` is 0.
1222 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);")]
1223 /// assert_eq!((-128i8).wrapping_div(-1), -128);
1225 #[stable(feature = "num_wrapping", since = "1.2.0")]
1226 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1227 #[must_use = "this returns the result of the operation, \
1228 without modifying the original"]
1230 pub const fn wrapping_div(self, rhs
: Self) -> Self {
1231 self.overflowing_div(rhs
).0
1234 /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
1235 /// wrapping around at the boundary of the type.
1237 /// Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1238 /// for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1239 /// type. In this case, this method returns `MIN` itself.
1243 /// This function will panic if `rhs` is 0.
1250 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);")]
1251 /// assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
1253 #[stable(feature = "euclidean_division", since = "1.38.0")]
1254 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1255 #[must_use = "this returns the result of the operation, \
1256 without modifying the original"]
1258 pub const fn wrapping_div_euclid(self, rhs
: Self) -> Self {
1259 self.overflowing_div_euclid(rhs
).0
1262 /// Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1263 /// boundary of the type.
1265 /// Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1266 /// invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1267 /// this function returns `0`.
1271 /// This function will panic if `rhs` is 0.
1278 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);")]
1279 /// assert_eq!((-128i8).wrapping_rem(-1), 0);
1281 #[stable(feature = "num_wrapping", since = "1.2.0")]
1282 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1283 #[must_use = "this returns the result of the operation, \
1284 without modifying the original"]
1286 pub const fn wrapping_rem(self, rhs
: Self) -> Self {
1287 self.overflowing_rem(rhs
).0
1290 /// Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
1291 /// at the boundary of the type.
1293 /// Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1294 /// for the type). In this case, this method returns 0.
1298 /// This function will panic if `rhs` is 0.
1305 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);")]
1306 /// assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
1308 #[stable(feature = "euclidean_division", since = "1.38.0")]
1309 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1310 #[must_use = "this returns the result of the operation, \
1311 without modifying the original"]
1313 pub const fn wrapping_rem_euclid(self, rhs
: Self) -> Self {
1314 self.overflowing_rem_euclid(rhs
).0
1317 /// Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1320 /// The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1321 /// is the negative minimal value for the type); this is a positive value that is too large to represent
1322 /// in the type. In such a case, this function returns `MIN` itself.
1329 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);")]
1330 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.wrapping_neg(), ", stringify!($SelfT), "::MIN);")]
1332 #[stable(feature = "num_wrapping", since = "1.2.0")]
1333 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1334 #[must_use = "this returns the result of the operation, \
1335 without modifying the original"]
1337 pub const fn wrapping_neg(self) -> Self {
1338 (0 as $SelfT
).wrapping_sub(self)
1341 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1342 /// any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1344 /// Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1345 /// the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1346 /// The primitive integer types all implement a [`rotate_left`](Self::rotate_left) function,
1347 /// which may be what you want instead.
1354 #[doc = concat!("assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);")]
1355 #[doc = concat!("assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);")]
1357 #[stable(feature = "num_wrapping", since = "1.2.0")]
1358 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1359 #[must_use = "this returns the result of the operation, \
1360 without modifying the original"]
1362 pub const fn wrapping_shl(self, rhs
: u32) -> Self {
1363 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1366 intrinsics
::unchecked_shl(self, (rhs
& ($BITS
- 1)) as $SelfT
)
1370 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1371 /// removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1373 /// Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1374 /// to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1375 /// end. The primitive integer types all implement a [`rotate_right`](Self::rotate_right) function,
1376 /// which may be what you want instead.
1383 #[doc = concat!("assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);")]
1384 /// assert_eq!((-128i16).wrapping_shr(64), -128);
1386 #[stable(feature = "num_wrapping", since = "1.2.0")]
1387 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1388 #[must_use = "this returns the result of the operation, \
1389 without modifying the original"]
1391 pub const fn wrapping_shr(self, rhs
: u32) -> Self {
1392 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1395 intrinsics
::unchecked_shr(self, (rhs
& ($BITS
- 1)) as $SelfT
)
1399 /// Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1400 /// the boundary of the type.
1402 /// The only case where such wrapping can occur is when one takes the absolute value of the negative
1403 /// minimal value for the type; this is a positive value that is too large to represent in the type. In
1404 /// such a case, this function returns `MIN` itself.
1411 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);")]
1412 #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);")]
1413 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.wrapping_abs(), ", stringify!($SelfT), "::MIN);")]
1414 /// assert_eq!((-128i8).wrapping_abs() as u8, 128);
1416 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1417 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1418 #[must_use = "this returns the result of the operation, \
1419 without modifying the original"]
1420 #[allow(unused_attributes)]
1422 pub const fn wrapping_abs(self) -> Self {
1423 if self.is_negative() {
1430 /// Computes the absolute value of `self` without any wrapping
1439 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".unsigned_abs(), 100", stringify!($UnsignedT), ");")]
1440 #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").unsigned_abs(), 100", stringify!($UnsignedT), ");")]
1441 /// assert_eq!((-128i8).unsigned_abs(), 128u8);
1443 #[stable(feature = "unsigned_abs", since = "1.51.0")]
1444 #[rustc_const_stable(feature = "unsigned_abs", since = "1.51.0")]
1445 #[must_use = "this returns the result of the operation, \
1446 without modifying the original"]
1448 pub const fn unsigned_abs(self) -> $UnsignedT
{
1449 self.wrapping_abs() as $UnsignedT
1452 /// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1453 /// wrapping around at the boundary of the type.
1460 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);")]
1461 /// assert_eq!(3i8.wrapping_pow(5), -13);
1462 /// assert_eq!(3i8.wrapping_pow(6), -39);
1464 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1465 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1466 #[must_use = "this returns the result of the operation, \
1467 without modifying the original"]
1469 pub const fn wrapping_pow(self, mut exp
: u32) -> Self {
1473 let mut base
= self;
1474 let mut acc
: Self = 1;
1478 acc
= acc
.wrapping_mul(base
);
1481 base
= base
.wrapping_mul(base
);
1484 // since exp!=0, finally the exp must be 1.
1485 // Deal with the final bit of the exponent separately, since
1486 // squaring the base afterwards is not necessary and may cause a
1487 // needless overflow.
1488 acc
.wrapping_mul(base
)
1491 /// Calculates `self` + `rhs`
1493 /// Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1494 /// occur. If an overflow would have occurred then the wrapped value is returned.
1502 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));")]
1503 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT), "::MIN, true));")]
1505 #[stable(feature = "wrapping", since = "1.7.0")]
1506 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1507 #[must_use = "this returns the result of the operation, \
1508 without modifying the original"]
1510 pub const fn overflowing_add(self, rhs
: Self) -> (Self, bool
) {
1511 let (a
, b
) = intrinsics
::add_with_overflow(self as $ActualT
, rhs
as $ActualT
);
1515 /// Calculates `self` + `rhs` with an unsigned `rhs`
1517 /// Returns a tuple of the addition along with a boolean indicating
1518 /// whether an arithmetic overflow would occur. If an overflow would
1519 /// have occurred then the wrapped value is returned.
1526 /// # #![feature(mixed_integer_ops)]
1527 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_unsigned(2), (3, false));")]
1528 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN).overflowing_add_unsigned(", stringify!($UnsignedT), "::MAX), (", stringify!($SelfT), "::MAX, false));")]
1529 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).overflowing_add_unsigned(3), (", stringify!($SelfT), "::MIN, true));")]
1531 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1532 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1533 #[must_use = "this returns the result of the operation, \
1534 without modifying the original"]
1536 pub const fn overflowing_add_unsigned(self, rhs
: $UnsignedT
) -> (Self, bool
) {
1537 let rhs
= rhs
as Self;
1538 let (res
, overflowed
) = self.overflowing_add(rhs
);
1539 (res
, overflowed ^
(rhs
< 0))
1542 /// Calculates `self` - `rhs`
1544 /// Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1545 /// would occur. If an overflow would have occurred then the wrapped value is returned.
1553 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));")]
1554 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")]
1556 #[stable(feature = "wrapping", since = "1.7.0")]
1557 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1558 #[must_use = "this returns the result of the operation, \
1559 without modifying the original"]
1561 pub const fn overflowing_sub(self, rhs
: Self) -> (Self, bool
) {
1562 let (a
, b
) = intrinsics
::sub_with_overflow(self as $ActualT
, rhs
as $ActualT
);
1566 /// Calculates `self` - `rhs` with an unsigned `rhs`
1568 /// Returns a tuple of the subtraction along with a boolean indicating
1569 /// whether an arithmetic overflow would occur. If an overflow would
1570 /// have occurred then the wrapped value is returned.
1577 /// # #![feature(mixed_integer_ops)]
1578 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_sub_unsigned(2), (-1, false));")]
1579 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX).overflowing_sub_unsigned(", stringify!($UnsignedT), "::MAX), (", stringify!($SelfT), "::MIN, false));")]
1580 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 2).overflowing_sub_unsigned(3), (", stringify!($SelfT), "::MAX, true));")]
1582 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1583 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1584 #[must_use = "this returns the result of the operation, \
1585 without modifying the original"]
1587 pub const fn overflowing_sub_unsigned(self, rhs
: $UnsignedT
) -> (Self, bool
) {
1588 let rhs
= rhs
as Self;
1589 let (res
, overflowed
) = self.overflowing_sub(rhs
);
1590 (res
, overflowed ^
(rhs
< 0))
1593 /// Calculates the multiplication of `self` and `rhs`.
1595 /// Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1596 /// would occur. If an overflow would have occurred then the wrapped value is returned.
1603 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));")]
1604 /// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
1606 #[stable(feature = "wrapping", since = "1.7.0")]
1607 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1608 #[must_use = "this returns the result of the operation, \
1609 without modifying the original"]
1611 pub const fn overflowing_mul(self, rhs
: Self) -> (Self, bool
) {
1612 let (a
, b
) = intrinsics
::mul_with_overflow(self as $ActualT
, rhs
as $ActualT
);
1616 /// Calculates the divisor when `self` is divided by `rhs`.
1618 /// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1619 /// occur. If an overflow would occur then self is returned.
1623 /// This function will panic if `rhs` is 0.
1631 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));")]
1632 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT), "::MIN, true));")]
1635 #[stable(feature = "wrapping", since = "1.7.0")]
1636 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1637 #[must_use = "this returns the result of the operation, \
1638 without modifying the original"]
1639 pub const fn overflowing_div(self, rhs
: Self) -> (Self, bool
) {
1640 // Using `&` helps LLVM see that it is the same check made in division.
1641 if unlikely
!((self == Self::MIN
) & (rhs
== -1)) {
1648 /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1650 /// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1651 /// occur. If an overflow would occur then `self` is returned.
1655 /// This function will panic if `rhs` is 0.
1662 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));")]
1663 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euclid(-1), (", stringify!($SelfT), "::MIN, true));")]
1666 #[stable(feature = "euclidean_division", since = "1.38.0")]
1667 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1668 #[must_use = "this returns the result of the operation, \
1669 without modifying the original"]
1670 pub const fn overflowing_div_euclid(self, rhs
: Self) -> (Self, bool
) {
1671 // Using `&` helps LLVM see that it is the same check made in division.
1672 if unlikely
!((self == Self::MIN
) & (rhs
== -1)) {
1675 (self.div_euclid(rhs
), false)
1679 /// Calculates the remainder when `self` is divided by `rhs`.
1681 /// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1682 /// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1686 /// This function will panic if `rhs` is 0.
1694 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));")]
1695 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));")]
1698 #[stable(feature = "wrapping", since = "1.7.0")]
1699 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1700 #[must_use = "this returns the result of the operation, \
1701 without modifying the original"]
1702 pub const fn overflowing_rem(self, rhs
: Self) -> (Self, bool
) {
1703 if unlikely
!(rhs
== -1) {
1704 (0, self == Self::MIN
)
1711 /// Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
1713 /// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1714 /// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1718 /// This function will panic if `rhs` is 0.
1725 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));")]
1726 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem_euclid(-1), (0, true));")]
1728 #[stable(feature = "euclidean_division", since = "1.38.0")]
1729 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1730 #[must_use = "this returns the result of the operation, \
1731 without modifying the original"]
1733 pub const fn overflowing_rem_euclid(self, rhs
: Self) -> (Self, bool
) {
1734 if unlikely
!(rhs
== -1) {
1735 (0, self == Self::MIN
)
1737 (self.rem_euclid(rhs
), false)
1742 /// Negates self, overflowing if this is equal to the minimum value.
1744 /// Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1745 /// happened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the
1746 /// minimum value will be returned again and `true` will be returned for an overflow happening.
1753 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));")]
1754 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT), "::MIN, true));")]
1757 #[stable(feature = "wrapping", since = "1.7.0")]
1758 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1759 #[must_use = "this returns the result of the operation, \
1760 without modifying the original"]
1761 #[allow(unused_attributes)]
1762 pub const fn overflowing_neg(self) -> (Self, bool
) {
1763 if unlikely
!(self == Self::MIN
) {
1770 /// Shifts self left by `rhs` bits.
1772 /// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1773 /// value was larger than or equal to the number of bits. If the shift value is too large, then value is
1774 /// masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1781 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));")]
1782 /// assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));
1784 #[stable(feature = "wrapping", since = "1.7.0")]
1785 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1786 #[must_use = "this returns the result of the operation, \
1787 without modifying the original"]
1789 pub const fn overflowing_shl(self, rhs
: u32) -> (Self, bool
) {
1790 (self.wrapping_shl(rhs
), (rhs
> ($BITS
- 1)))
1793 /// Shifts self right by `rhs` bits.
1795 /// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1796 /// value was larger than or equal to the number of bits. If the shift value is too large, then value is
1797 /// masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1804 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));")]
1805 /// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
1807 #[stable(feature = "wrapping", since = "1.7.0")]
1808 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1809 #[must_use = "this returns the result of the operation, \
1810 without modifying the original"]
1812 pub const fn overflowing_shr(self, rhs
: u32) -> (Self, bool
) {
1813 (self.wrapping_shr(rhs
), (rhs
> ($BITS
- 1)))
1816 /// Computes the absolute value of `self`.
1818 /// Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1819 /// happened. If self is the minimum value
1820 #[doc = concat!("(e.g., ", stringify!($SelfT), "::MIN for values of type ", stringify!($SelfT), "),")]
1821 /// then the minimum value will be returned again and true will be returned
1822 /// for an overflow happening.
1829 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));")]
1830 #[doc = concat!("assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));")]
1831 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN).overflowing_abs(), (", stringify!($SelfT), "::MIN, true));")]
1833 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1834 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1835 #[must_use = "this returns the result of the operation, \
1836 without modifying the original"]
1838 pub const fn overflowing_abs(self) -> (Self, bool
) {
1839 (self.wrapping_abs(), self == Self::MIN
)
1842 /// Raises self to the power of `exp`, using exponentiation by squaring.
1844 /// Returns a tuple of the exponentiation along with a bool indicating
1845 /// whether an overflow happened.
1852 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));")]
1853 /// assert_eq!(3i8.overflowing_pow(5), (-13, true));
1855 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1856 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1857 #[must_use = "this returns the result of the operation, \
1858 without modifying the original"]
1860 pub const fn overflowing_pow(self, mut exp
: u32) -> (Self, bool
) {
1864 let mut base
= self;
1865 let mut acc
: Self = 1;
1866 let mut overflown
= false;
1867 // Scratch space for storing results of overflowing_mul.
1872 r
= acc
.overflowing_mul(base
);
1877 r
= base
.overflowing_mul(base
);
1882 // since exp!=0, finally the exp must be 1.
1883 // Deal with the final bit of the exponent separately, since
1884 // squaring the base afterwards is not necessary and may cause a
1885 // needless overflow.
1886 r
= acc
.overflowing_mul(base
);
1891 /// Raises self to the power of `exp`, using exponentiation by squaring.
1898 #[doc = concat!("let x: ", stringify!($SelfT), " = 2; // or any other integer type")]
1900 /// assert_eq!(x.pow(5), 32);
1902 #[stable(feature = "rust1", since = "1.0.0")]
1903 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1904 #[must_use = "this returns the result of the operation, \
1905 without modifying the original"]
1907 #[rustc_inherit_overflow_checks]
1908 pub const fn pow(self, mut exp
: u32) -> Self {
1912 let mut base
= self;
1923 // since exp!=0, finally the exp must be 1.
1924 // Deal with the final bit of the exponent separately, since
1925 // squaring the base afterwards is not necessary and may cause a
1926 // needless overflow.
1930 /// Calculates the quotient of Euclidean division of `self` by `rhs`.
1932 /// This computes the integer `q` such that `self = q * rhs + r`, with
1933 /// `r = self.rem_euclid(rhs)` and `0 <= r < abs(rhs)`.
1935 /// In other words, the result is `self / rhs` rounded to the integer `q`
1936 /// such that `self >= q * rhs`.
1937 /// If `self > 0`, this is equal to round towards zero (the default in Rust);
1938 /// if `self < 0`, this is equal to round towards +/- infinity.
1942 /// This function will panic if `rhs` is 0 or the division results in overflow.
1949 #[doc = concat!("let a: ", stringify!($SelfT), " = 7; // or any other integer type")]
1952 /// assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
1953 /// assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
1954 /// assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
1955 /// assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
1957 #[stable(feature = "euclidean_division", since = "1.38.0")]
1958 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1959 #[must_use = "this returns the result of the operation, \
1960 without modifying the original"]
1962 #[rustc_inherit_overflow_checks]
1963 pub const fn div_euclid(self, rhs
: Self) -> Self {
1966 return if rhs
> 0 { q - 1 }
else { q + 1 }
1972 /// Calculates the least nonnegative remainder of `self (mod rhs)`.
1974 /// This is done as if by the Euclidean division algorithm -- given
1975 /// `r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) + r`, and
1976 /// `0 <= r < abs(rhs)`.
1980 /// This function will panic if `rhs` is 0 or the division results in overflow.
1987 #[doc = concat!("let a: ", stringify!($SelfT), " = 7; // or any other integer type")]
1990 /// assert_eq!(a.rem_euclid(b), 3);
1991 /// assert_eq!((-a).rem_euclid(b), 1);
1992 /// assert_eq!(a.rem_euclid(-b), 3);
1993 /// assert_eq!((-a).rem_euclid(-b), 1);
1995 #[stable(feature = "euclidean_division", since = "1.38.0")]
1996 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1997 #[must_use = "this returns the result of the operation, \
1998 without modifying the original"]
2000 #[rustc_inherit_overflow_checks]
2001 pub const fn rem_euclid(self, rhs
: Self) -> Self {
2014 /// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
2018 /// This function will panic if `rhs` is zero.
2020 /// ## Overflow behavior
2022 /// On overflow, this function will panic if overflow checks are enabled (default in debug
2023 /// mode) and wrap if overflow checks are disabled (default in release mode).
2030 /// #![feature(int_roundings)]
2031 #[doc = concat!("let a: ", stringify!($SelfT)," = 8;")]
2034 /// assert_eq!(a.div_floor(b), 2);
2035 /// assert_eq!(a.div_floor(-b), -3);
2036 /// assert_eq!((-a).div_floor(b), -3);
2037 /// assert_eq!((-a).div_floor(-b), 2);
2039 #[unstable(feature = "int_roundings", issue = "88581")]
2040 #[must_use = "this returns the result of the operation, \
2041 without modifying the original"]
2043 #[rustc_inherit_overflow_checks]
2044 pub const fn div_floor(self, rhs
: Self) -> Self {
2047 if (r
> 0 && rhs
< 0) || (r
< 0 && rhs
> 0) {
2054 /// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
2058 /// This function will panic if `rhs` is zero.
2060 /// ## Overflow behavior
2062 /// On overflow, this function will panic if overflow checks are enabled (default in debug
2063 /// mode) and wrap if overflow checks are disabled (default in release mode).
2070 /// #![feature(int_roundings)]
2071 #[doc = concat!("let a: ", stringify!($SelfT)," = 8;")]
2074 /// assert_eq!(a.div_ceil(b), 3);
2075 /// assert_eq!(a.div_ceil(-b), -2);
2076 /// assert_eq!((-a).div_ceil(b), -2);
2077 /// assert_eq!((-a).div_ceil(-b), 3);
2079 #[unstable(feature = "int_roundings", issue = "88581")]
2080 #[must_use = "this returns the result of the operation, \
2081 without modifying the original"]
2083 #[rustc_inherit_overflow_checks]
2084 pub const fn div_ceil(self, rhs
: Self) -> Self {
2087 if (r
> 0 && rhs
> 0) || (r
< 0 && rhs
< 0) {
2094 /// If `rhs` is positive, calculates the smallest value greater than or
2095 /// equal to `self` that is a multiple of `rhs`. If `rhs` is negative,
2096 /// calculates the largest value less than or equal to `self` that is a
2097 /// multiple of `rhs`.
2101 /// This function will panic if `rhs` is zero.
2103 /// ## Overflow behavior
2105 /// On overflow, this function will panic if overflow checks are enabled (default in debug
2106 /// mode) and wrap if overflow checks are disabled (default in release mode).
2113 /// #![feature(int_roundings)]
2114 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".next_multiple_of(8), 16);")]
2115 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".next_multiple_of(8), 24);")]
2116 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".next_multiple_of(-8), 16);")]
2117 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".next_multiple_of(-8), 16);")]
2118 #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").next_multiple_of(8), -16);")]
2119 #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").next_multiple_of(8), -16);")]
2120 #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").next_multiple_of(-8), -16);")]
2121 #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").next_multiple_of(-8), -24);")]
2123 #[unstable(feature = "int_roundings", issue = "88581")]
2124 #[must_use = "this returns the result of the operation, \
2125 without modifying the original"]
2127 #[rustc_inherit_overflow_checks]
2128 pub const fn next_multiple_of(self, rhs
: Self) -> Self {
2129 // This would otherwise fail when calculating `r` when self == T::MIN.
2135 let m
= if (r
> 0 && rhs
< 0) || (r
< 0 && rhs
> 0) {
2148 /// If `rhs` is positive, calculates the smallest value greater than or
2149 /// equal to `self` that is a multiple of `rhs`. If `rhs` is negative,
2150 /// calculates the largest value less than or equal to `self` that is a
2151 /// multiple of `rhs`. Returns `None` if `rhs` is zero or the operation
2152 /// would result in overflow.
2159 /// #![feature(int_roundings)]
2160 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(16));")]
2161 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(24));")]
2162 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(-8), Some(16));")]
2163 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(-8), Some(16));")]
2164 #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").checked_next_multiple_of(8), Some(-16));")]
2165 #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").checked_next_multiple_of(8), Some(-16));")]
2166 #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").checked_next_multiple_of(-8), Some(-16));")]
2167 #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").checked_next_multiple_of(-8), Some(-24));")]
2168 #[doc = concat!("assert_eq!(1_", stringify!($SelfT), ".checked_next_multiple_of(0), None);")]
2169 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_multiple_of(2), None);")]
2171 #[unstable(feature = "int_roundings", issue = "88581")]
2172 #[must_use = "this returns the result of the operation, \
2173 without modifying the original"]
2175 pub const fn checked_next_multiple_of(self, rhs
: Self) -> Option
<Self> {
2176 // This would otherwise fail when calculating `r` when self == T::MIN.
2181 let r
= try_opt
!(self.checked_rem(rhs
));
2182 let m
= if (r
> 0 && rhs
< 0) || (r
< 0 && rhs
> 0) {
2183 // r + rhs cannot overflow because they have opposite signs
2192 // rhs - m cannot overflow because m has the same sign as rhs
2193 self.checked_add(rhs
- m
)
2197 /// Returns the logarithm of the number with respect to an arbitrary base,
2200 /// This method might not be optimized owing to implementation details;
2201 /// `log2` can produce results more efficiently for base 2, and `log10`
2202 /// can produce results more efficiently for base 10.
2206 /// When the number is negative, zero, or if the base is not at least 2; it
2207 /// panics in debug mode and the return value is 0 in release
2213 /// #![feature(int_log)]
2214 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".log(5), 1);")]
2216 #[unstable(feature = "int_log", issue = "70887")]
2217 #[must_use = "this returns the result of the operation, \
2218 without modifying the original"]
2221 #[rustc_inherit_overflow_checks]
2222 #[allow(arithmetic_overflow)]
2223 pub const fn log(self, base
: Self) -> u32 {
2224 match self.checked_log(base
) {
2227 // In debug builds, trigger a panic on None.
2228 // This should optimize completely out in release builds.
2229 let _
= Self::MAX
+ 1;
2236 /// Returns the base 2 logarithm of the number, rounded down.
2240 /// When the number is negative or zero it panics in debug mode and the return value
2241 /// is 0 in release mode.
2246 /// #![feature(int_log)]
2247 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".log2(), 1);")]
2249 #[unstable(feature = "int_log", issue = "70887")]
2250 #[must_use = "this returns the result of the operation, \
2251 without modifying the original"]
2254 #[rustc_inherit_overflow_checks]
2255 #[allow(arithmetic_overflow)]
2256 pub const fn log2(self) -> u32 {
2257 match self.checked_log2() {
2260 // In debug builds, trigger a panic on None.
2261 // This should optimize completely out in release builds.
2262 let _
= Self::MAX
+ 1;
2269 /// Returns the base 10 logarithm of the number, rounded down.
2273 /// When the number is negative or zero it panics in debug mode and the return value
2274 /// is 0 in release mode.
2279 /// #![feature(int_log)]
2280 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".log10(), 1);")]
2282 #[unstable(feature = "int_log", issue = "70887")]
2283 #[must_use = "this returns the result of the operation, \
2284 without modifying the original"]
2287 #[rustc_inherit_overflow_checks]
2288 #[allow(arithmetic_overflow)]
2289 pub const fn log10(self) -> u32 {
2290 match self.checked_log10() {
2293 // In debug builds, trigger a panic on None.
2294 // This should optimize completely out in release builds.
2295 let _
= Self::MAX
+ 1;
2302 /// Returns the logarithm of the number with respect to an arbitrary base,
2305 /// Returns `None` if the number is negative or zero, or if the base is not at least 2.
2307 /// This method might not be optimized owing to implementation details;
2308 /// `checked_log2` can produce results more efficiently for base 2, and
2309 /// `checked_log10` can produce results more efficiently for base 10.
2314 /// #![feature(int_log)]
2315 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_log(5), Some(1));")]
2317 #[unstable(feature = "int_log", issue = "70887")]
2318 #[must_use = "this returns the result of the operation, \
2319 without modifying the original"]
2321 pub const fn checked_log(self, base
: Self) -> Option
<u32> {
2322 if self <= 0 || base
<= 1 {
2328 // Optimization for 128 bit wide integers.
2329 if Self::BITS
== 128 {
2330 let b
= Self::log2(self) / (Self::log2(base
) + 1);
2332 r
/= base
.pow(b
as u32);
2343 /// Returns the base 2 logarithm of the number, rounded down.
2345 /// Returns `None` if the number is negative or zero.
2350 /// #![feature(int_log)]
2351 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_log2(), Some(1));")]
2353 #[unstable(feature = "int_log", issue = "70887")]
2354 #[must_use = "this returns the result of the operation, \
2355 without modifying the original"]
2357 pub const fn checked_log2(self) -> Option
<u32> {
2361 // SAFETY: We just checked that this number is positive
2362 let log
= (Self::BITS
- 1) - unsafe { intrinsics::ctlz_nonzero(self) as u32 }
;
2367 /// Returns the base 10 logarithm of the number, rounded down.
2369 /// Returns `None` if the number is negative or zero.
2374 /// #![feature(int_log)]
2375 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_log10(), Some(1));")]
2377 #[unstable(feature = "int_log", issue = "70887")]
2378 #[must_use = "this returns the result of the operation, \
2379 without modifying the original"]
2381 pub const fn checked_log10(self) -> Option
<u32> {
2383 Some(int_log10
::$
ActualT(self as $ActualT
))
2389 /// Computes the absolute value of `self`.
2391 /// # Overflow behavior
2393 /// The absolute value of
2394 #[doc = concat!("`", stringify!($SelfT), "::MIN`")]
2395 /// cannot be represented as an
2396 #[doc = concat!("`", stringify!($SelfT), "`,")]
2397 /// and attempting to calculate it will cause an overflow. This means
2398 /// that code in debug mode will trigger a panic on this case and
2399 /// optimized code will return
2400 #[doc = concat!("`", stringify!($SelfT), "::MIN`")]
2401 /// without a panic.
2408 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".abs(), 10);")]
2409 #[doc = concat!("assert_eq!((-10", stringify!($SelfT), ").abs(), 10);")]
2411 #[stable(feature = "rust1", since = "1.0.0")]
2412 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2413 #[allow(unused_attributes)]
2414 #[must_use = "this returns the result of the operation, \
2415 without modifying the original"]
2417 #[rustc_inherit_overflow_checks]
2418 pub const fn abs(self) -> Self {
2419 // Note that the #[rustc_inherit_overflow_checks] and #[inline]
2420 // above mean that the overflow semantics of the subtraction
2421 // depend on the crate we're being called from.
2422 if self.is_negative() {
2429 /// Computes the absolute difference between `self` and `other`.
2431 /// This function always returns the correct answer without overflow or
2432 /// panics by returning an unsigned integer.
2439 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(80), 20", stringify!($UnsignedT), ");")]
2440 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(110), 10", stringify!($UnsignedT), ");")]
2441 #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").abs_diff(80), 180", stringify!($UnsignedT), ");")]
2442 #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").abs_diff(-120), 20", stringify!($UnsignedT), ");")]
2443 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.abs_diff(", stringify!($SelfT), "::MAX), ", stringify!($UnsignedT), "::MAX);")]
2445 #[stable(feature = "int_abs_diff", since = "1.60.0")]
2446 #[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
2447 #[must_use = "this returns the result of the operation, \
2448 without modifying the original"]
2450 pub const fn abs_diff(self, other
: Self) -> $UnsignedT
{
2452 // Converting a non-negative x from signed to unsigned by using
2453 // `x as U` is left unchanged, but a negative x is converted
2454 // to value x + 2^N. Thus if `s` and `o` are binary variables
2455 // respectively indicating whether `self` and `other` are
2456 // negative, we are computing the mathematical value:
2458 // (other + o*2^N) - (self + s*2^N) mod 2^N
2459 // other - self + (o-s)*2^N mod 2^N
2460 // other - self mod 2^N
2462 // Finally, taking the mod 2^N of the mathematical value of
2463 // `other - self` does not change it as it already is
2464 // in the range [0, 2^N).
2465 (other
as $UnsignedT
).wrapping_sub(self as $UnsignedT
)
2467 (self as $UnsignedT
).wrapping_sub(other
as $UnsignedT
)
2471 /// Returns a number representing sign of `self`.
2473 /// - `0` if the number is zero
2474 /// - `1` if the number is positive
2475 /// - `-1` if the number is negative
2482 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".signum(), 1);")]
2483 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".signum(), 0);")]
2484 #[doc = concat!("assert_eq!((-10", stringify!($SelfT), ").signum(), -1);")]
2486 #[stable(feature = "rust1", since = "1.0.0")]
2487 #[rustc_const_stable(feature = "const_int_sign", since = "1.47.0")]
2488 #[must_use = "this returns the result of the operation, \
2489 without modifying the original"]
2491 pub const fn signum(self) -> Self {
2499 /// Returns `true` if `self` is positive and `false` if the number is zero or
2507 #[doc = concat!("assert!(10", stringify!($SelfT), ".is_positive());")]
2508 #[doc = concat!("assert!(!(-10", stringify!($SelfT), ").is_positive());")]
2511 #[stable(feature = "rust1", since = "1.0.0")]
2512 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2514 pub const fn is_positive(self) -> bool { self > 0 }
2516 /// Returns `true` if `self` is negative and `false` if the number is zero or
2524 #[doc = concat!("assert!((-10", stringify!($SelfT), ").is_negative());")]
2525 #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_negative());")]
2528 #[stable(feature = "rust1", since = "1.0.0")]
2529 #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2531 pub const fn is_negative(self) -> bool { self < 0 }
2533 /// Return the memory representation of this integer as a byte array in
2534 /// big-endian (network) byte order.
2536 #[doc = $to_xe_bytes_doc]
2541 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();")]
2542 #[doc = concat!("assert_eq!(bytes, ", $be_bytes, ");")]
2544 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2545 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2546 #[must_use = "this returns the result of the operation, \
2547 without modifying the original"]
2549 pub const fn to_be_bytes(self) -> [u8; mem
::size_of
::<Self>()] {
2550 self.to_be().to_ne_bytes()
2553 /// Return the memory representation of this integer as a byte array in
2554 /// little-endian byte order.
2556 #[doc = $to_xe_bytes_doc]
2561 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();")]
2562 #[doc = concat!("assert_eq!(bytes, ", $le_bytes, ");")]
2564 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2565 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2566 #[must_use = "this returns the result of the operation, \
2567 without modifying the original"]
2569 pub const fn to_le_bytes(self) -> [u8; mem
::size_of
::<Self>()] {
2570 self.to_le().to_ne_bytes()
2573 /// Return the memory representation of this integer as a byte array in
2574 /// native byte order.
2576 /// As the target platform's native endianness is used, portable code
2577 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2580 #[doc = $to_xe_bytes_doc]
2582 /// [`to_be_bytes`]: Self::to_be_bytes
2583 /// [`to_le_bytes`]: Self::to_le_bytes
2588 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();")]
2591 /// if cfg!(target_endian = "big") {
2592 #[doc = concat!(" ", $be_bytes)]
2594 #[doc = concat!(" ", $le_bytes)]
2598 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2599 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2600 // SAFETY: const sound because integers are plain old datatypes so we can always
2601 // transmute them to arrays of bytes
2602 #[must_use = "this returns the result of the operation, \
2603 without modifying the original"]
2605 pub const fn to_ne_bytes(self) -> [u8; mem
::size_of
::<Self>()] {
2606 // SAFETY: integers are plain old datatypes so we can always transmute them to
2608 unsafe { mem::transmute(self) }
2611 /// Create an integer value from its representation as a byte array in
2614 #[doc = $to_xe_bytes_doc]
2619 #[doc = concat!("let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");")]
2620 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2623 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2626 #[doc = concat!("fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2627 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2629 #[doc = concat!(" ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())")]
2632 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2633 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2636 pub const fn from_be_bytes(bytes
: [u8; mem
::size_of
::<Self>()]) -> Self {
2637 Self::from_be(Self::from_ne_bytes(bytes
))
2640 /// Create an integer value from its representation as a byte array in
2643 #[doc = $to_xe_bytes_doc]
2648 #[doc = concat!("let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");")]
2649 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2652 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2655 #[doc = concat!("fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2656 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2658 #[doc = concat!(" ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())")]
2661 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2662 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2665 pub const fn from_le_bytes(bytes
: [u8; mem
::size_of
::<Self>()]) -> Self {
2666 Self::from_le(Self::from_ne_bytes(bytes
))
2669 /// Create an integer value from its memory representation as a byte
2670 /// array in native endianness.
2672 /// As the target platform's native endianness is used, portable code
2673 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2674 /// appropriate instead.
2676 /// [`from_be_bytes`]: Self::from_be_bytes
2677 /// [`from_le_bytes`]: Self::from_le_bytes
2679 #[doc = $to_xe_bytes_doc]
2684 #[doc = concat!("let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {")]
2685 #[doc = concat!(" ", $be_bytes)]
2687 #[doc = concat!(" ", $le_bytes)]
2689 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2692 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2695 #[doc = concat!("fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2696 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2698 #[doc = concat!(" ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())")]
2701 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2702 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2704 // SAFETY: const sound because integers are plain old datatypes so we can always
2705 // transmute to them
2707 pub const fn from_ne_bytes(bytes
: [u8; mem
::size_of
::<Self>()]) -> Self {
2708 // SAFETY: integers are plain old datatypes so we can always transmute to them
2709 unsafe { mem::transmute(bytes) }
2712 /// New code should prefer to use
2713 #[doc = concat!("[`", stringify!($SelfT), "::MIN", "`] instead.")]
2715 /// Returns the smallest value that can be represented by this integer type.
2716 #[stable(feature = "rust1", since = "1.0.0")]
2719 #[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
2720 #[deprecated(since = "TBD", note = "replaced by the `MIN` associated constant on this type")]
2721 pub const fn min_value() -> Self {
2725 /// New code should prefer to use
2726 #[doc = concat!("[`", stringify!($SelfT), "::MAX", "`] instead.")]
2728 /// Returns the largest value that can be represented by this integer type.
2729 #[stable(feature = "rust1", since = "1.0.0")]
2732 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2733 #[deprecated(since = "TBD", note = "replaced by the `MAX` associated constant on this type")]
2734 pub const fn max_value() -> Self {