1 macro_rules! uint_impl {
2 ($SelfT:ty, $ActualT:ident, $SignedT:ident, $BITS:expr, $MaxV: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.
13 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN, 0);")]
15 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
16 pub const MIN: Self = 0;
18 /// The largest value that can be represented by this integer type,
19 #[doc = concat!("2<sup>", $BITS, "</sup> - 1.")]
26 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($MaxV), ");")]
28 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
29 pub const MAX: Self = !0;
31 /// The size of this integer type in bits.
36 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::BITS, ", stringify!($BITS), ");")]
38 #[stable(feature = "int_bits_const", since = "1.53.0")]
39 pub const BITS: u32 = $BITS;
41 /// Converts a string slice in a given base to an integer.
43 /// The string is expected to be an optional `+` sign
44 /// followed by digits.
45 /// Leading and trailing whitespace represent an error.
46 /// Digits are a subset of these characters, 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 = 0b01001100", stringify!($SelfT), ";")]
77 /// assert_eq!(n.count_ones(), 3);
79 #[stable(feature = "rust1", since = "1.0.0")]
80 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
81 #[doc(alias = "popcount")]
82 #[doc(alias = "popcnt")]
83 #[must_use = "this returns the result of the operation, \
84 without modifying the original"]
86 pub const fn count_ones(self) -> u32 {
87 intrinsics::ctpop(self as $ActualT) as u32
90 /// Returns the number of zeros in the binary representation of `self`.
97 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.count_zeros(), 0);")]
99 #[stable(feature = "rust1", since = "1.0.0")]
100 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
101 #[must_use = "this returns the result of the operation, \
102 without modifying the original"]
104 pub const fn count_zeros(self) -> u32 {
108 /// Returns the number of leading zeros in the binary representation of `self`.
115 #[doc = concat!("let n = ", stringify!($SelfT), "::MAX >> 2;")]
117 /// assert_eq!(n.leading_zeros(), 2);
119 #[stable(feature = "rust1", since = "1.0.0")]
120 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
121 #[must_use = "this returns the result of the operation, \
122 without modifying the original"]
124 pub const fn leading_zeros(self) -> u32 {
125 intrinsics::ctlz(self as $ActualT) as u32
128 /// Returns the number of trailing zeros in the binary representation
136 #[doc = concat!("let n = 0b0101000", stringify!($SelfT), ";")]
138 /// assert_eq!(n.trailing_zeros(), 3);
140 #[stable(feature = "rust1", since = "1.0.0")]
141 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
142 #[must_use = "this returns the result of the operation, \
143 without modifying the original"]
145 pub const fn trailing_zeros(self) -> u32 {
146 intrinsics::cttz(self) as u32
149 /// Returns the number of leading ones in the binary representation of `self`.
156 #[doc = concat!("let n = !(", stringify!($SelfT), "::MAX >> 2);")]
158 /// assert_eq!(n.leading_ones(), 2);
160 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
161 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
162 #[must_use = "this returns the result of the operation, \
163 without modifying the original"]
165 pub const fn leading_ones(self) -> u32 {
166 (!self).leading_zeros()
169 /// Returns the number of trailing ones in the binary representation
177 #[doc = concat!("let n = 0b1010111", stringify!($SelfT), ";")]
179 /// assert_eq!(n.trailing_ones(), 3);
181 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
182 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
183 #[must_use = "this returns the result of the operation, \
184 without modifying the original"]
186 pub const fn trailing_ones(self) -> u32 {
187 (!self).trailing_zeros()
190 /// Shifts the bits to the left by a specified amount, `n`,
191 /// wrapping the truncated bits to the end of the resulting integer.
193 /// Please note this isn't the same operation as the `<<` shifting operator!
200 #[doc = concat!("let n = ", $rot_op, stringify!($SelfT), ";")]
201 #[doc = concat!("let m = ", $rot_result, ";")]
203 #[doc = concat!("assert_eq!(n.rotate_left(", $rot, "), m);")]
205 #[stable(feature = "rust1", since = "1.0.0")]
206 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
207 #[must_use = "this returns the result of the operation, \
208 without modifying the original"]
210 pub const fn rotate_left(self, n: u32) -> Self {
211 intrinsics::rotate_left(self, n as $SelfT)
214 /// Shifts the bits to the right by a specified amount, `n`,
215 /// wrapping the truncated bits to the beginning of the resulting
218 /// Please note this isn't the same operation as the `>>` shifting operator!
225 #[doc = concat!("let n = ", $rot_result, stringify!($SelfT), ";")]
226 #[doc = concat!("let m = ", $rot_op, ";")]
228 #[doc = concat!("assert_eq!(n.rotate_right(", $rot, "), m);")]
230 #[stable(feature = "rust1", since = "1.0.0")]
231 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
232 #[must_use = "this returns the result of the operation, \
233 without modifying the original"]
235 pub const fn rotate_right(self, n: u32) -> Self {
236 intrinsics::rotate_right(self, n as $SelfT)
239 /// Reverses the byte order of the integer.
246 #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
247 /// let m = n.swap_bytes();
249 #[doc = concat!("assert_eq!(m, ", $swapped, ");")]
251 #[stable(feature = "rust1", since = "1.0.0")]
252 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
253 #[must_use = "this returns the result of the operation, \
254 without modifying the original"]
256 pub const fn swap_bytes(self) -> Self {
257 intrinsics::bswap(self as $ActualT) as Self
260 /// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
261 /// second least-significant bit becomes second most-significant bit, etc.
268 #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
269 /// let m = n.reverse_bits();
271 #[doc = concat!("assert_eq!(m, ", $reversed, ");")]
272 #[doc = concat!("assert_eq!(0, 0", stringify!($SelfT), ".reverse_bits());")]
274 #[stable(feature = "reverse_bits", since = "1.37.0")]
275 #[rustc_const_stable(feature = "const_math", since = "1.37.0")]
276 #[must_use = "this returns the result of the operation, \
277 without modifying the original"]
279 pub const fn reverse_bits(self) -> Self {
280 intrinsics::bitreverse(self as $ActualT) as Self
283 /// Converts an integer from big endian to the target's endianness.
285 /// On big endian this is a no-op. On little endian the bytes are
293 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
295 /// if cfg!(target_endian = "big") {
296 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_be(n), n)")]
298 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())")]
301 #[stable(feature = "rust1", since = "1.0.0")]
302 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
305 pub const fn from_be(x: Self) -> Self {
306 #[cfg(target_endian = "big")]
310 #[cfg(not(target_endian = "big"))]
316 /// Converts an integer from little endian to the target's endianness.
318 /// On little endian this is a no-op. On big endian the bytes are
326 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
328 /// if cfg!(target_endian = "little") {
329 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_le(n), n)")]
331 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())")]
334 #[stable(feature = "rust1", since = "1.0.0")]
335 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
338 pub const fn from_le(x: Self) -> Self {
339 #[cfg(target_endian = "little")]
343 #[cfg(not(target_endian = "little"))]
349 /// Converts `self` to big endian from the target's endianness.
351 /// On big endian this is a no-op. On little endian the bytes are
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_math", 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
393 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
395 /// if cfg!(target_endian = "little") {
396 /// assert_eq!(n.to_le(), n)
398 /// assert_eq!(n.to_le(), n.swap_bytes())
401 #[stable(feature = "rust1", since = "1.0.0")]
402 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
403 #[must_use = "this returns the result of the operation, \
404 without modifying the original"]
406 pub const fn to_le(self) -> Self {
407 #[cfg(target_endian = "little")]
411 #[cfg(not(target_endian = "little"))]
417 /// Checked integer addition. Computes `self + rhs`, returning `None`
418 /// if overflow occurred.
426 "assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(1), ",
427 "Some(", stringify!($SelfT), "::MAX - 1));"
429 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);")]
431 #[stable(feature = "rust1", since = "1.0.0")]
432 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
433 #[must_use = "this returns the result of the operation, \
434 without modifying the original"]
436 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
437 let (a, b) = self.overflowing_add(rhs);
438 if unlikely!(b) {None} else {Some(a)}
441 /// Unchecked integer addition. Computes `self + rhs`, assuming overflow
446 /// This results in undefined behavior when
447 #[doc = concat!("`self + rhs > ", stringify!($SelfT), "::MAX` or `self + rhs < ", stringify!($SelfT), "::MIN`,")]
448 /// i.e. when [`checked_add`] would return `None`.
450 #[doc = concat!("[`checked_add`]: ", stringify!($SelfT), "::checked_add")]
452 feature = "unchecked_math",
453 reason = "niche optimization path",
456 #[must_use = "this returns the result of the operation, \
457 without modifying the original"]
458 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
460 pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
461 // SAFETY: the caller must uphold the safety contract for
463 unsafe { intrinsics::unchecked_add(self, rhs) }
466 /// Checked addition with a signed integer. Computes `self + rhs`,
467 /// returning `None` if overflow occurred.
474 /// # #![feature(mixed_integer_ops)]
475 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_add_signed(2), Some(3));")]
476 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_add_signed(-2), None);")]
477 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add_signed(3), None);")]
479 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
480 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
481 #[must_use = "this returns the result of the operation, \
482 without modifying the original"]
484 pub const fn checked_add_signed(self, rhs: $SignedT) -> Option<Self> {
485 let (a, b) = self.overflowing_add_signed(rhs);
486 if unlikely!(b) {None} else {Some(a)}
489 /// Checked integer subtraction. Computes `self - rhs`, returning
490 /// `None` if overflow occurred.
497 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));")]
498 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);")]
500 #[stable(feature = "rust1", since = "1.0.0")]
501 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
502 #[must_use = "this returns the result of the operation, \
503 without modifying the original"]
505 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
506 let (a, b) = self.overflowing_sub(rhs);
507 if unlikely!(b) {None} else {Some(a)}
510 /// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
515 /// This results in undefined behavior when
516 #[doc = concat!("`self - rhs > ", stringify!($SelfT), "::MAX` or `self - rhs < ", stringify!($SelfT), "::MIN`,")]
517 /// i.e. when [`checked_sub`] would return `None`.
519 #[doc = concat!("[`checked_sub`]: ", stringify!($SelfT), "::checked_sub")]
521 feature = "unchecked_math",
522 reason = "niche optimization path",
525 #[must_use = "this returns the result of the operation, \
526 without modifying the original"]
527 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
529 pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
530 // SAFETY: the caller must uphold the safety contract for
532 unsafe { intrinsics::unchecked_sub(self, rhs) }
535 /// Checked integer multiplication. Computes `self * rhs`, returning
536 /// `None` if overflow occurred.
543 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));")]
544 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);")]
546 #[stable(feature = "rust1", since = "1.0.0")]
547 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
548 #[must_use = "this returns the result of the operation, \
549 without modifying the original"]
551 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
552 let (a, b) = self.overflowing_mul(rhs);
553 if unlikely!(b) {None} else {Some(a)}
556 /// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
561 /// This results in undefined behavior when
562 #[doc = concat!("`self * rhs > ", stringify!($SelfT), "::MAX` or `self * rhs < ", stringify!($SelfT), "::MIN`,")]
563 /// i.e. when [`checked_mul`] would return `None`.
565 #[doc = concat!("[`checked_mul`]: ", stringify!($SelfT), "::checked_mul")]
567 feature = "unchecked_math",
568 reason = "niche optimization path",
571 #[must_use = "this returns the result of the operation, \
572 without modifying the original"]
573 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
575 pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
576 // SAFETY: the caller must uphold the safety contract for
578 unsafe { intrinsics::unchecked_mul(self, rhs) }
581 /// Checked integer division. Computes `self / rhs`, returning `None`
589 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));")]
590 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);")]
592 #[stable(feature = "rust1", since = "1.0.0")]
593 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.52.0")]
594 #[must_use = "this returns the result of the operation, \
595 without modifying the original"]
597 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
598 if unlikely!(rhs == 0) {
601 // SAFETY: div by zero has been checked above and unsigned types have no other
602 // failure modes for division
603 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
607 /// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
615 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));")]
616 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);")]
618 #[stable(feature = "euclidean_division", since = "1.38.0")]
619 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
620 #[must_use = "this returns the result of the operation, \
621 without modifying the original"]
623 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
624 if unlikely!(rhs == 0) {
627 Some(self.div_euclid(rhs))
632 /// Checked integer remainder. Computes `self % rhs`, returning `None`
640 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));")]
641 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);")]
643 #[stable(feature = "wrapping", since = "1.7.0")]
644 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.52.0")]
645 #[must_use = "this returns the result of the operation, \
646 without modifying the original"]
648 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
649 if unlikely!(rhs == 0) {
652 // SAFETY: div by zero has been checked above and unsigned types have no other
653 // failure modes for division
654 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
658 /// Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
666 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));")]
667 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);")]
669 #[stable(feature = "euclidean_division", since = "1.38.0")]
670 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
671 #[must_use = "this returns the result of the operation, \
672 without modifying the original"]
674 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
675 if unlikely!(rhs == 0) {
678 Some(self.rem_euclid(rhs))
682 /// Returns the logarithm of the number with respect to an arbitrary base,
685 /// This method might not be optimized owing to implementation details;
686 /// `log2` can produce results more efficiently for base 2, and `log10`
687 /// can produce results more efficiently for base 10.
691 /// When the number is negative, zero, or if the base is not at least 2;
692 /// it panics in debug mode and the return value is 0 in release mode.
697 /// #![feature(int_log)]
698 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".log(5), 1);")]
700 #[unstable(feature = "int_log", issue = "70887")]
701 #[must_use = "this returns the result of the operation, \
702 without modifying the original"]
705 #[rustc_inherit_overflow_checks]
706 #[allow(arithmetic_overflow)]
707 pub const fn log(self, base: Self) -> u32 {
708 match self.checked_log(base) {
711 // In debug builds, trigger a panic on None.
712 // This should optimize completely out in release builds.
713 let _ = Self::MAX + 1;
720 /// Returns the base 2 logarithm of the number, rounded down.
724 /// When the number is negative or zero it panics in debug mode and
725 /// the return value is 0 in release mode.
730 /// #![feature(int_log)]
731 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".log2(), 1);")]
733 #[unstable(feature = "int_log", issue = "70887")]
734 #[must_use = "this returns the result of the operation, \
735 without modifying the original"]
738 #[rustc_inherit_overflow_checks]
739 #[allow(arithmetic_overflow)]
740 pub const fn log2(self) -> u32 {
741 match self.checked_log2() {
744 // In debug builds, trigger a panic on None.
745 // This should optimize completely out in release builds.
746 let _ = Self::MAX + 1;
753 /// Returns the base 10 logarithm of the number, rounded down.
757 /// When the number is negative or zero it panics in debug mode and the
758 /// return value is 0 in release mode.
763 /// #![feature(int_log)]
764 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".log10(), 1);")]
766 #[unstable(feature = "int_log", issue = "70887")]
767 #[must_use = "this returns the result of the operation, \
768 without modifying the original"]
771 #[rustc_inherit_overflow_checks]
772 #[allow(arithmetic_overflow)]
773 pub const fn log10(self) -> u32 {
774 match self.checked_log10() {
777 // In debug builds, trigger a panic on None.
778 // This should optimize completely out in release builds.
779 let _ = Self::MAX + 1;
786 /// Returns the logarithm of the number with respect to an arbitrary base,
789 /// Returns `None` if the number is zero, or if the base is not at least 2.
791 /// This method might not be optimized owing to implementation details;
792 /// `checked_log2` can produce results more efficiently for base 2, and
793 /// `checked_log10` can produce results more efficiently for base 10.
798 /// #![feature(int_log)]
799 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_log(5), Some(1));")]
801 #[unstable(feature = "int_log", issue = "70887")]
802 #[must_use = "this returns the result of the operation, \
803 without modifying the original"]
805 pub const fn checked_log(self, base: Self) -> Option<u32> {
806 if self <= 0 || base <= 1 {
812 // Optimization for 128 bit wide integers.
813 if Self::BITS == 128 {
814 let b = Self::log2(self) / (Self::log2(base) + 1);
816 r /= base.pow(b as u32);
827 /// Returns the base 2 logarithm of the number, rounded down.
829 /// Returns `None` if the number is zero.
834 /// #![feature(int_log)]
835 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_log2(), Some(1));")]
837 #[unstable(feature = "int_log", issue = "70887")]
838 #[must_use = "this returns the result of the operation, \
839 without modifying the original"]
841 pub const fn checked_log2(self) -> Option<u32> {
845 // SAFETY: We just checked that this number is positive
846 let log = (Self::BITS - 1) - unsafe { intrinsics::ctlz_nonzero(self) as u32 };
851 /// Returns the base 10 logarithm of the number, rounded down.
853 /// Returns `None` if the number is zero.
858 /// #![feature(int_log)]
859 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_log10(), Some(1));")]
861 #[unstable(feature = "int_log", issue = "70887")]
862 #[must_use = "this returns the result of the operation, \
863 without modifying the original"]
865 pub const fn checked_log10(self) -> Option<u32> {
866 int_log10::$ActualT(self as $ActualT)
869 /// Checked negation. Computes `-self`, returning `None` unless `self ==
872 /// Note that negating any positive integer will overflow.
879 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));")]
880 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);")]
882 #[stable(feature = "wrapping", since = "1.7.0")]
883 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
884 #[must_use = "this returns the result of the operation, \
885 without modifying the original"]
887 pub const fn checked_neg(self) -> Option<Self> {
888 let (a, b) = self.overflowing_neg();
889 if unlikely!(b) {None} else {Some(a)}
892 /// Checked shift left. Computes `self << rhs`, returning `None`
893 /// if `rhs` is larger than or equal to the number of bits in `self`.
900 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));")]
901 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);")]
903 #[stable(feature = "wrapping", since = "1.7.0")]
904 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
905 #[must_use = "this returns the result of the operation, \
906 without modifying the original"]
908 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
909 let (a, b) = self.overflowing_shl(rhs);
910 if unlikely!(b) {None} else {Some(a)}
913 /// Unchecked shift left. Computes `self << rhs`, assuming that
914 /// `rhs` is less than the number of bits in `self`.
918 /// This results in undefined behavior if `rhs` is larger than
919 /// or equal to the number of bits in `self`,
920 /// i.e. when [`checked_shl`] would return `None`.
922 #[doc = concat!("[`checked_shl`]: ", stringify!($SelfT), "::checked_shl")]
924 feature = "unchecked_math",
925 reason = "niche optimization path",
928 #[must_use = "this returns the result of the operation, \
929 without modifying the original"]
930 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
932 pub const unsafe fn unchecked_shl(self, rhs: Self) -> Self {
933 // SAFETY: the caller must uphold the safety contract for
935 unsafe { intrinsics::unchecked_shl(self, rhs) }
938 /// Checked shift right. Computes `self >> rhs`, returning `None`
939 /// if `rhs` is larger than or equal to the number of bits in `self`.
946 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));")]
947 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);")]
949 #[stable(feature = "wrapping", since = "1.7.0")]
950 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
951 #[must_use = "this returns the result of the operation, \
952 without modifying the original"]
954 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
955 let (a, b) = self.overflowing_shr(rhs);
956 if unlikely!(b) {None} else {Some(a)}
959 /// Unchecked shift right. Computes `self >> rhs`, assuming that
960 /// `rhs` is less than the number of bits in `self`.
964 /// This results in undefined behavior if `rhs` is larger than
965 /// or equal to the number of bits in `self`,
966 /// i.e. when [`checked_shr`] would return `None`.
968 #[doc = concat!("[`checked_shr`]: ", stringify!($SelfT), "::checked_shr")]
970 feature = "unchecked_math",
971 reason = "niche optimization path",
974 #[must_use = "this returns the result of the operation, \
975 without modifying the original"]
976 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
978 pub const unsafe fn unchecked_shr(self, rhs: Self) -> Self {
979 // SAFETY: the caller must uphold the safety contract for
981 unsafe { intrinsics::unchecked_shr(self, rhs) }
984 /// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
985 /// overflow occurred.
992 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));")]
993 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);")]
995 #[stable(feature = "no_panic_pow", since = "1.34.0")]
996 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
997 #[must_use = "this returns the result of the operation, \
998 without modifying the original"]
1000 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
1004 let mut base = self;
1005 let mut acc: Self = 1;
1009 acc = try_opt!(acc.checked_mul(base));
1012 base = try_opt!(base.checked_mul(base));
1015 // since exp!=0, finally the exp must be 1.
1016 // Deal with the final bit of the exponent separately, since
1017 // squaring the base afterwards is not necessary and may cause a
1018 // needless overflow.
1020 Some(try_opt!(acc.checked_mul(base)))
1023 /// Saturating integer addition. Computes `self + rhs`, saturating at
1024 /// the numeric bounds instead of overflowing.
1031 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);")]
1032 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(127), ", stringify!($SelfT), "::MAX);")]
1034 #[stable(feature = "rust1", since = "1.0.0")]
1035 #[must_use = "this returns the result of the operation, \
1036 without modifying the original"]
1037 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1039 pub const fn saturating_add(self, rhs: Self) -> Self {
1040 intrinsics::saturating_add(self, rhs)
1043 /// Saturating addition with a signed integer. Computes `self + rhs`,
1044 /// saturating at the numeric bounds instead of overflowing.
1051 /// # #![feature(mixed_integer_ops)]
1052 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_signed(2), 3);")]
1053 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_signed(-2), 0);")]
1054 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).saturating_add_signed(4), ", stringify!($SelfT), "::MAX);")]
1056 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1057 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1058 #[must_use = "this returns the result of the operation, \
1059 without modifying the original"]
1061 pub const fn saturating_add_signed(self, rhs: $SignedT) -> Self {
1062 let (res, overflow) = self.overflowing_add(rhs as Self);
1063 if overflow == (rhs < 0) {
1065 } else if overflow {
1072 /// Saturating integer subtraction. Computes `self - rhs`, saturating
1073 /// at the numeric bounds instead of overflowing.
1080 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);")]
1081 #[doc = concat!("assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);")]
1083 #[stable(feature = "rust1", since = "1.0.0")]
1084 #[must_use = "this returns the result of the operation, \
1085 without modifying the original"]
1086 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1088 pub const fn saturating_sub(self, rhs: Self) -> Self {
1089 intrinsics::saturating_sub(self, rhs)
1092 /// Saturating integer multiplication. Computes `self * rhs`,
1093 /// saturating at the numeric bounds instead of overflowing.
1100 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);")]
1101 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),"::MAX);")]
1103 #[stable(feature = "wrapping", since = "1.7.0")]
1104 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1105 #[must_use = "this returns the result of the operation, \
1106 without modifying the original"]
1108 pub const fn saturating_mul(self, rhs: Self) -> Self {
1109 match self.checked_mul(rhs) {
1115 /// Saturating integer division. Computes `self / rhs`, saturating at the
1116 /// numeric bounds instead of overflowing.
1123 /// #![feature(saturating_div)]
1125 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".saturating_div(2), 2);")]
1130 /// #![feature(saturating_div)]
1132 #[doc = concat!("let _ = 1", stringify!($SelfT), ".saturating_div(0);")]
1135 #[unstable(feature = "saturating_div", issue = "87920")]
1136 #[rustc_const_unstable(feature = "saturating_div", issue = "87920")]
1137 #[must_use = "this returns the result of the operation, \
1138 without modifying the original"]
1140 pub const fn saturating_div(self, rhs: Self) -> Self {
1141 // on unsigned types, there is no overflow in integer division
1142 self.wrapping_div(rhs)
1145 /// Saturating integer exponentiation. Computes `self.pow(exp)`,
1146 /// saturating at the numeric bounds instead of overflowing.
1153 #[doc = concat!("assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);")]
1154 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);")]
1156 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1157 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1158 #[must_use = "this returns the result of the operation, \
1159 without modifying the original"]
1161 pub const fn saturating_pow(self, exp: u32) -> Self {
1162 match self.checked_pow(exp) {
1168 /// Wrapping (modular) addition. Computes `self + rhs`,
1169 /// wrapping around at the boundary of the type.
1176 #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);")]
1177 #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);")]
1179 #[stable(feature = "rust1", since = "1.0.0")]
1180 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1181 #[must_use = "this returns the result of the operation, \
1182 without modifying the original"]
1184 pub const fn wrapping_add(self, rhs: Self) -> Self {
1185 intrinsics::wrapping_add(self, rhs)
1188 /// Wrapping (modular) addition with a signed integer. Computes
1189 /// `self + rhs`, wrapping around at the boundary of the type.
1196 /// # #![feature(mixed_integer_ops)]
1197 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_add_signed(2), 3);")]
1198 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_add_signed(-2), ", stringify!($SelfT), "::MAX);")]
1199 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).wrapping_add_signed(4), 1);")]
1201 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1202 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1203 #[must_use = "this returns the result of the operation, \
1204 without modifying the original"]
1206 pub const fn wrapping_add_signed(self, rhs: $SignedT) -> Self {
1207 self.wrapping_add(rhs as Self)
1210 /// Wrapping (modular) subtraction. Computes `self - rhs`,
1211 /// wrapping around at the boundary of the type.
1218 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);")]
1219 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::MAX), 101);")]
1221 #[stable(feature = "rust1", since = "1.0.0")]
1222 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1223 #[must_use = "this returns the result of the operation, \
1224 without modifying the original"]
1226 pub const fn wrapping_sub(self, rhs: Self) -> Self {
1227 intrinsics::wrapping_sub(self, rhs)
1230 /// Wrapping (modular) multiplication. Computes `self *
1231 /// rhs`, wrapping around at the boundary of the type.
1237 /// Please note that this example is shared between integer types.
1238 /// Which explains why `u8` is used here.
1241 /// assert_eq!(10u8.wrapping_mul(12), 120);
1242 /// assert_eq!(25u8.wrapping_mul(12), 44);
1244 #[stable(feature = "rust1", since = "1.0.0")]
1245 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1246 #[must_use = "this returns the result of the operation, \
1247 without modifying the original"]
1249 pub const fn wrapping_mul(self, rhs: Self) -> Self {
1250 intrinsics::wrapping_mul(self, rhs)
1253 /// Wrapping (modular) division. Computes `self / rhs`.
1254 /// Wrapped division on unsigned types is just normal division.
1255 /// There's no way wrapping could ever happen.
1256 /// This function exists, so that all operations
1257 /// are accounted for in the wrapping operations.
1264 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);")]
1266 #[stable(feature = "num_wrapping", since = "1.2.0")]
1267 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1268 #[must_use = "this returns the result of the operation, \
1269 without modifying the original"]
1271 pub const fn wrapping_div(self, rhs: Self) -> Self {
1275 /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
1276 /// Wrapped division on unsigned types is just normal division.
1277 /// There's no way wrapping could ever happen.
1278 /// This function exists, so that all operations
1279 /// are accounted for in the wrapping operations.
1280 /// Since, for the positive integers, all common
1281 /// definitions of division are equal, this
1282 /// is exactly equal to `self.wrapping_div(rhs)`.
1289 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);")]
1291 #[stable(feature = "euclidean_division", since = "1.38.0")]
1292 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1293 #[must_use = "this returns the result of the operation, \
1294 without modifying the original"]
1296 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
1300 /// Wrapping (modular) remainder. Computes `self % rhs`.
1301 /// Wrapped remainder calculation on unsigned types is
1302 /// just the regular remainder calculation.
1303 /// There's no way wrapping could ever happen.
1304 /// This function exists, so that all operations
1305 /// are accounted for in the wrapping operations.
1312 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);")]
1314 #[stable(feature = "num_wrapping", since = "1.2.0")]
1315 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1316 #[must_use = "this returns the result of the operation, \
1317 without modifying the original"]
1319 pub const fn wrapping_rem(self, rhs: Self) -> Self {
1323 /// Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
1324 /// Wrapped modulo calculation on unsigned types is
1325 /// just the regular remainder calculation.
1326 /// There's no way wrapping could ever happen.
1327 /// This function exists, so that all operations
1328 /// are accounted for in the wrapping operations.
1329 /// Since, for the positive integers, all common
1330 /// definitions of division are equal, this
1331 /// is exactly equal to `self.wrapping_rem(rhs)`.
1338 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);")]
1340 #[stable(feature = "euclidean_division", since = "1.38.0")]
1341 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1342 #[must_use = "this returns the result of the operation, \
1343 without modifying the original"]
1345 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1349 /// Wrapping (modular) negation. Computes `-self`,
1350 /// wrapping around at the boundary of the type.
1352 /// Since unsigned types do not have negative equivalents
1353 /// all applications of this function will wrap (except for `-0`).
1354 /// For values smaller than the corresponding signed type's maximum
1355 /// the result is the same as casting the corresponding signed value.
1356 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
1357 /// `MAX` is the corresponding signed type's maximum.
1363 /// Please note that this example is shared between integer types.
1364 /// Which explains why `i8` is used here.
1367 /// assert_eq!(100i8.wrapping_neg(), -100);
1368 /// assert_eq!((-128i8).wrapping_neg(), -128);
1370 #[stable(feature = "num_wrapping", since = "1.2.0")]
1371 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1372 #[must_use = "this returns the result of the operation, \
1373 without modifying the original"]
1375 pub const fn wrapping_neg(self) -> Self {
1376 (0 as $SelfT).wrapping_sub(self)
1379 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1380 /// where `mask` removes any high-order bits of `rhs` that
1381 /// would cause the shift to exceed the bitwidth of the type.
1383 /// Note that this is *not* the same as a rotate-left; the
1384 /// RHS of a wrapping shift-left is restricted to the range
1385 /// of the type, rather than the bits shifted out of the LHS
1386 /// being returned to the other end. The primitive integer
1387 /// types all implement a [`rotate_left`](Self::rotate_left) function,
1388 /// which may be what you want instead.
1395 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);")]
1396 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);")]
1398 #[stable(feature = "num_wrapping", since = "1.2.0")]
1399 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1400 #[must_use = "this returns the result of the operation, \
1401 without modifying the original"]
1403 pub const fn wrapping_shl(self, rhs: u32) -> Self {
1404 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1407 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1411 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
1412 /// where `mask` removes any high-order bits of `rhs` that
1413 /// would cause the shift to exceed the bitwidth of the type.
1415 /// Note that this is *not* the same as a rotate-right; the
1416 /// RHS of a wrapping shift-right is restricted to the range
1417 /// of the type, rather than the bits shifted out of the LHS
1418 /// being returned to the other end. The primitive integer
1419 /// types all implement a [`rotate_right`](Self::rotate_right) function,
1420 /// which may be what you want instead.
1427 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);")]
1428 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);")]
1430 #[stable(feature = "num_wrapping", since = "1.2.0")]
1431 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1432 #[must_use = "this returns the result of the operation, \
1433 without modifying the original"]
1435 pub const fn wrapping_shr(self, rhs: u32) -> Self {
1436 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1439 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1443 /// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1444 /// wrapping around at the boundary of the type.
1451 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);")]
1452 /// assert_eq!(3u8.wrapping_pow(6), 217);
1454 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1455 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1456 #[must_use = "this returns the result of the operation, \
1457 without modifying the original"]
1459 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
1463 let mut base = self;
1464 let mut acc: Self = 1;
1468 acc = acc.wrapping_mul(base);
1471 base = base.wrapping_mul(base);
1474 // since exp!=0, finally the exp must be 1.
1475 // Deal with the final bit of the exponent separately, since
1476 // squaring the base afterwards is not necessary and may cause a
1477 // needless overflow.
1478 acc.wrapping_mul(base)
1481 /// Calculates `self` + `rhs`
1483 /// Returns a tuple of the addition along with a boolean indicating
1484 /// whether an arithmetic overflow would occur. If an overflow would
1485 /// have occurred then the wrapped value is returned.
1493 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));")]
1494 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));")]
1496 #[stable(feature = "wrapping", since = "1.7.0")]
1497 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1498 #[must_use = "this returns the result of the operation, \
1499 without modifying the original"]
1501 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1502 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1506 /// Calculates `self + rhs + carry` without the ability to overflow.
1508 /// Performs "ternary addition" which takes in an extra bit to add, and may return an
1509 /// additional bit of overflow. This allows for chaining together multiple additions
1510 /// to create "big integers" which represent larger values.
1517 /// #![feature(bigint_helper_methods)]
1518 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".carrying_add(2, false), (7, false));")]
1519 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".carrying_add(2, true), (8, false));")]
1520 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.carrying_add(1, false), (0, true));")]
1521 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.carrying_add(1, true), (1, true));")]
1523 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
1524 #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")]
1525 #[must_use = "this returns the result of the operation, \
1526 without modifying the original"]
1528 pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
1529 // note: longer-term this should be done via an intrinsic, but this has been shown
1530 // to generate optimal code for now, and LLVM doesn't have an equivalent intrinsic
1531 let (a, b) = self.overflowing_add(rhs);
1532 let (c, d) = a.overflowing_add(carry as $SelfT);
1536 /// Calculates `self` + `rhs` with a signed `rhs`
1538 /// Returns a tuple of the addition along with a boolean indicating
1539 /// whether an arithmetic overflow would occur. If an overflow would
1540 /// have occurred then the wrapped value is returned.
1547 /// # #![feature(mixed_integer_ops)]
1548 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_signed(2), (3, false));")]
1549 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_signed(-2), (", stringify!($SelfT), "::MAX, true));")]
1550 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).overflowing_add_signed(4), (1, true));")]
1552 #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1553 #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1554 #[must_use = "this returns the result of the operation, \
1555 without modifying the original"]
1557 pub const fn overflowing_add_signed(self, rhs: $SignedT) -> (Self, bool) {
1558 let (res, overflowed) = self.overflowing_add(rhs as Self);
1559 (res, overflowed ^ (rhs < 0))
1562 /// Calculates `self` - `rhs`
1564 /// Returns a tuple of the subtraction along with a boolean indicating
1565 /// whether an arithmetic overflow would occur. If an overflow would
1566 /// have occurred then the wrapped value is returned.
1574 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));")]
1575 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")]
1577 #[stable(feature = "wrapping", since = "1.7.0")]
1578 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1579 #[must_use = "this returns the result of the operation, \
1580 without modifying the original"]
1582 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1583 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1587 /// Calculates `self - rhs - borrow` without the ability to overflow.
1589 /// Performs "ternary subtraction" which takes in an extra bit to subtract, and may return
1590 /// an additional bit of overflow. This allows for chaining together multiple subtractions
1591 /// to create "big integers" which represent larger values.
1598 /// #![feature(bigint_helper_methods)]
1599 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".borrowing_sub(2, false), (3, false));")]
1600 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".borrowing_sub(2, true), (2, false));")]
1601 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".borrowing_sub(1, false), (", stringify!($SelfT), "::MAX, true));")]
1602 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".borrowing_sub(1, true), (", stringify!($SelfT), "::MAX - 1, true));")]
1604 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
1605 #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")]
1606 #[must_use = "this returns the result of the operation, \
1607 without modifying the original"]
1609 pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
1610 // note: longer-term this should be done via an intrinsic, but this has been shown
1611 // to generate optimal code for now, and LLVM doesn't have an equivalent intrinsic
1612 let (a, b) = self.overflowing_sub(rhs);
1613 let (c, d) = a.overflowing_sub(borrow as $SelfT);
1617 /// Computes the absolute difference between `self` and `other`.
1624 /// #![feature(int_abs_diff)]
1625 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(80), 20", stringify!($SelfT), ");")]
1626 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(110), 10", stringify!($SelfT), ");")]
1628 #[unstable(feature = "int_abs_diff", issue = "89492")]
1629 #[must_use = "this returns the result of the operation, \
1630 without modifying the original"]
1632 pub const fn abs_diff(self, other: Self) -> Self {
1633 if mem::size_of::<Self>() == 1 {
1634 // Trick LLVM into generating the psadbw instruction when SSE2
1635 // is available and this function is autovectorized for u8's.
1636 (self as i32).wrapping_sub(other as i32).abs() as Self
1646 /// Calculates the multiplication of `self` and `rhs`.
1648 /// Returns a tuple of the multiplication along with a boolean
1649 /// indicating whether an arithmetic overflow would occur. If an
1650 /// overflow would have occurred then the wrapped value is returned.
1656 /// Please note that this example is shared between integer types.
1657 /// Which explains why `u32` is used here.
1660 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
1661 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
1663 #[stable(feature = "wrapping", since = "1.7.0")]
1664 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1665 #[must_use = "this returns the result of the operation, \
1666 without modifying the original"]
1668 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1669 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1673 /// Calculates the divisor when `self` is divided by `rhs`.
1675 /// Returns a tuple of the divisor along with a boolean indicating
1676 /// whether an arithmetic overflow would occur. Note that for unsigned
1677 /// integers overflow never occurs, so the second value is always
1682 /// This function will panic if `rhs` is 0.
1689 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));")]
1692 #[stable(feature = "wrapping", since = "1.7.0")]
1693 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1694 #[must_use = "this returns the result of the operation, \
1695 without modifying the original"]
1696 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1700 /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1702 /// Returns a tuple of the divisor along with a boolean indicating
1703 /// whether an arithmetic overflow would occur. Note that for unsigned
1704 /// integers overflow never occurs, so the second value is always
1706 /// Since, for the positive integers, all common
1707 /// definitions of division are equal, this
1708 /// is exactly equal to `self.overflowing_div(rhs)`.
1712 /// This function will panic if `rhs` is 0.
1719 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));")]
1722 #[stable(feature = "euclidean_division", since = "1.38.0")]
1723 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1724 #[must_use = "this returns the result of the operation, \
1725 without modifying the original"]
1726 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1730 /// Calculates the remainder when `self` is divided by `rhs`.
1732 /// Returns a tuple of the remainder after dividing along with a boolean
1733 /// indicating whether an arithmetic overflow would occur. Note that for
1734 /// unsigned integers overflow never occurs, so the second value is
1739 /// This function will panic if `rhs` is 0.
1746 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));")]
1749 #[stable(feature = "wrapping", since = "1.7.0")]
1750 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1751 #[must_use = "this returns the result of the operation, \
1752 without modifying the original"]
1753 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1757 /// Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
1759 /// Returns a tuple of the modulo after dividing along with a boolean
1760 /// indicating whether an arithmetic overflow would occur. Note that for
1761 /// unsigned integers overflow never occurs, so the second value is
1763 /// Since, for the positive integers, all common
1764 /// definitions of division are equal, this operation
1765 /// is exactly equal to `self.overflowing_rem(rhs)`.
1769 /// This function will panic if `rhs` is 0.
1776 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));")]
1779 #[stable(feature = "euclidean_division", since = "1.38.0")]
1780 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1781 #[must_use = "this returns the result of the operation, \
1782 without modifying the original"]
1783 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1787 /// Negates self in an overflowing fashion.
1789 /// Returns `!self + 1` using wrapping operations to return the value
1790 /// that represents the negation of this unsigned value. Note that for
1791 /// positive unsigned values overflow always occurs, but negating 0 does
1799 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));")]
1800 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT), ", true));")]
1803 #[stable(feature = "wrapping", since = "1.7.0")]
1804 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1805 #[must_use = "this returns the result of the operation, \
1806 without modifying the original"]
1807 pub const fn overflowing_neg(self) -> (Self, bool) {
1808 ((!self).wrapping_add(1), self != 0)
1811 /// Shifts self left by `rhs` bits.
1813 /// Returns a tuple of the shifted version of self along with a boolean
1814 /// indicating whether the shift value was larger than or equal to the
1815 /// number of bits. If the shift value is too large, then value is
1816 /// masked (N-1) where N is the number of bits, and this value is then
1817 /// used to perform the shift.
1824 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));")]
1825 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));")]
1827 #[stable(feature = "wrapping", since = "1.7.0")]
1828 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1829 #[must_use = "this returns the result of the operation, \
1830 without modifying the original"]
1832 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1833 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1836 /// Shifts self right by `rhs` bits.
1838 /// Returns a tuple of the shifted version of self along with a boolean
1839 /// indicating whether the shift value was larger than or equal to the
1840 /// number of bits. If the shift value is too large, then value is
1841 /// masked (N-1) where N is the number of bits, and this value is then
1842 /// used to perform the shift.
1849 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));")]
1850 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));")]
1852 #[stable(feature = "wrapping", since = "1.7.0")]
1853 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1854 #[must_use = "this returns the result of the operation, \
1855 without modifying the original"]
1857 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1858 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1861 /// Raises self to the power of `exp`, using exponentiation by squaring.
1863 /// Returns a tuple of the exponentiation along with a bool indicating
1864 /// whether an overflow happened.
1871 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));")]
1872 /// assert_eq!(3u8.overflowing_pow(6), (217, true));
1874 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1875 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1876 #[must_use = "this returns the result of the operation, \
1877 without modifying the original"]
1879 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1883 let mut base = self;
1884 let mut acc: Self = 1;
1885 let mut overflown = false;
1886 // Scratch space for storing results of overflowing_mul.
1891 r = acc.overflowing_mul(base);
1896 r = base.overflowing_mul(base);
1901 // since exp!=0, finally the exp must be 1.
1902 // Deal with the final bit of the exponent separately, since
1903 // squaring the base afterwards is not necessary and may cause a
1904 // needless overflow.
1905 r = acc.overflowing_mul(base);
1911 /// Raises self to the power of `exp`, using exponentiation by squaring.
1918 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".pow(5), 32);")]
1920 #[stable(feature = "rust1", since = "1.0.0")]
1921 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1922 #[must_use = "this returns the result of the operation, \
1923 without modifying the original"]
1925 #[rustc_inherit_overflow_checks]
1926 pub const fn pow(self, mut exp: u32) -> Self {
1930 let mut base = self;
1941 // since exp!=0, finally the exp must be 1.
1942 // Deal with the final bit of the exponent separately, since
1943 // squaring the base afterwards is not necessary and may cause a
1944 // needless overflow.
1948 /// Performs Euclidean division.
1950 /// Since, for the positive integers, all common
1951 /// definitions of division are equal, this
1952 /// is exactly equal to `self / rhs`.
1956 /// This function will panic if `rhs` is 0.
1963 #[doc = concat!("assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type")]
1965 #[stable(feature = "euclidean_division", since = "1.38.0")]
1966 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1967 #[must_use = "this returns the result of the operation, \
1968 without modifying the original"]
1970 #[rustc_inherit_overflow_checks]
1971 pub const fn div_euclid(self, rhs: Self) -> Self {
1976 /// Calculates the least remainder of `self (mod rhs)`.
1978 /// Since, for the positive integers, all common
1979 /// definitions of division are equal, this
1980 /// is exactly equal to `self % rhs`.
1984 /// This function will panic if `rhs` is 0.
1991 #[doc = concat!("assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type")]
1993 #[stable(feature = "euclidean_division", since = "1.38.0")]
1994 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1995 #[must_use = "this returns the result of the operation, \
1996 without modifying the original"]
1998 #[rustc_inherit_overflow_checks]
1999 pub const fn rem_euclid(self, rhs: Self) -> Self {
2003 /// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
2005 /// This is the same as performing `self / rhs` for all unsigned integers.
2009 /// This function will panic if `rhs` is 0.
2016 /// #![feature(int_roundings)]
2017 #[doc = concat!("assert_eq!(7_", stringify!($SelfT), ".unstable_div_floor(4), 1);")]
2019 #[unstable(feature = "int_roundings", issue = "88581")]
2020 #[must_use = "this returns the result of the operation, \
2021 without modifying the original"]
2023 #[rustc_inherit_overflow_checks]
2024 pub const fn unstable_div_floor(self, rhs: Self) -> Self {
2028 /// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
2032 /// This function will panic if `rhs` is 0.
2039 /// #![feature(int_roundings)]
2040 #[doc = concat!("assert_eq!(7_", stringify!($SelfT), ".unstable_div_ceil(4), 2);")]
2042 #[unstable(feature = "int_roundings", issue = "88581")]
2043 #[must_use = "this returns the result of the operation, \
2044 without modifying the original"]
2046 #[rustc_inherit_overflow_checks]
2047 pub const fn unstable_div_ceil(self, rhs: Self) -> Self {
2050 if r > 0 && rhs > 0 {
2057 /// Calculates the smallest value greater than or equal to `self` that
2058 /// is a multiple of `rhs`.
2062 /// This function will panic if `rhs` is 0 or the operation results in overflow.
2069 /// #![feature(int_roundings)]
2070 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".unstable_next_multiple_of(8), 16);")]
2071 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".unstable_next_multiple_of(8), 24);")]
2073 #[unstable(feature = "int_roundings", issue = "88581")]
2074 #[must_use = "this returns the result of the operation, \
2075 without modifying the original"]
2077 #[rustc_inherit_overflow_checks]
2078 pub const fn unstable_next_multiple_of(self, rhs: Self) -> Self {
2081 r => self + (rhs - r)
2085 /// Calculates the smallest value greater than or equal to `self` that
2086 /// is a multiple of `rhs`. Returns `None` is `rhs` is zero or the
2087 /// operation would result in overflow.
2094 /// #![feature(int_roundings)]
2095 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(16));")]
2096 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(24));")]
2097 #[doc = concat!("assert_eq!(1_", stringify!($SelfT), ".checked_next_multiple_of(0), None);")]
2098 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_multiple_of(2), None);")]
2100 #[unstable(feature = "int_roundings", issue = "88581")]
2101 #[must_use = "this returns the result of the operation, \
2102 without modifying the original"]
2104 #[rustc_inherit_overflow_checks]
2105 pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
2106 match try_opt!(self.checked_rem(rhs)) {
2108 r => self.checked_add(try_opt!(rhs.checked_sub(r)))
2112 /// Returns `true` if and only if `self == 2^k` for some `k`.
2119 #[doc = concat!("assert!(16", stringify!($SelfT), ".is_power_of_two());")]
2120 #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_power_of_two());")]
2123 #[stable(feature = "rust1", since = "1.0.0")]
2124 #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
2126 pub const fn is_power_of_two(self) -> bool {
2127 self.count_ones() == 1
2130 // Returns one less than next power of two.
2131 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
2133 // 8u8.one_less_than_next_power_of_two() == 7
2134 // 6u8.one_less_than_next_power_of_two() == 7
2136 // This method cannot overflow, as in the `next_power_of_two`
2137 // overflow cases it instead ends up returning the maximum value
2138 // of the type, and can return 0 for 0.
2140 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2141 const fn one_less_than_next_power_of_two(self) -> Self {
2142 if self <= 1 { return 0; }
2145 // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros.
2146 // That means the shift is always in-bounds, and some processors
2147 // (such as intel pre-haswell) have more efficient ctlz
2148 // intrinsics when the argument is non-zero.
2149 let z = unsafe { intrinsics::ctlz_nonzero(p) };
2153 /// Returns the smallest power of two greater than or equal to `self`.
2155 /// When return value overflows (i.e., `self > (1 << (N-1))` for type
2156 /// `uN`), it panics in debug mode and the return value is wrapped to 0 in
2157 /// release mode (the only situation in which method can return 0).
2164 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);")]
2165 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);")]
2167 #[stable(feature = "rust1", since = "1.0.0")]
2168 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2169 #[must_use = "this returns the result of the operation, \
2170 without modifying the original"]
2172 #[rustc_inherit_overflow_checks]
2173 pub const fn next_power_of_two(self) -> Self {
2174 self.one_less_than_next_power_of_two() + 1
2177 /// Returns the smallest power of two greater than or equal to `n`. If
2178 /// the next power of two is greater than the type's maximum value,
2179 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
2186 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_next_power_of_two(), Some(2));")]
2187 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));")]
2188 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_power_of_two(), None);")]
2191 #[stable(feature = "rust1", since = "1.0.0")]
2192 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2193 #[must_use = "this returns the result of the operation, \
2194 without modifying the original"]
2195 pub const fn checked_next_power_of_two(self) -> Option<Self> {
2196 self.one_less_than_next_power_of_two().checked_add(1)
2199 /// Returns the smallest power of two greater than or equal to `n`. If
2200 /// the next power of two is greater than the type's maximum value,
2201 /// the return value is wrapped to `0`.
2208 /// #![feature(wrapping_next_power_of_two)]
2210 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);")]
2211 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);")]
2212 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_next_power_of_two(), 0);")]
2214 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
2215 reason = "needs decision on wrapping behaviour")]
2216 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2217 #[must_use = "this returns the result of the operation, \
2218 without modifying the original"]
2219 pub const fn wrapping_next_power_of_two(self) -> Self {
2220 self.one_less_than_next_power_of_two().wrapping_add(1)
2223 /// Return the memory representation of this integer as a byte array in
2224 /// big-endian (network) byte order.
2226 #[doc = $to_xe_bytes_doc]
2231 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();")]
2232 #[doc = concat!("assert_eq!(bytes, ", $be_bytes, ");")]
2234 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2235 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2236 #[must_use = "this returns the result of the operation, \
2237 without modifying the original"]
2239 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2240 self.to_be().to_ne_bytes()
2243 /// Return the memory representation of this integer as a byte array in
2244 /// little-endian byte order.
2246 #[doc = $to_xe_bytes_doc]
2251 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();")]
2252 #[doc = concat!("assert_eq!(bytes, ", $le_bytes, ");")]
2254 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2255 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2256 #[must_use = "this returns the result of the operation, \
2257 without modifying the original"]
2259 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2260 self.to_le().to_ne_bytes()
2263 /// Return the memory representation of this integer as a byte array in
2264 /// native byte order.
2266 /// As the target platform's native endianness is used, portable code
2267 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2270 #[doc = $to_xe_bytes_doc]
2272 /// [`to_be_bytes`]: Self::to_be_bytes
2273 /// [`to_le_bytes`]: Self::to_le_bytes
2278 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();")]
2281 /// if cfg!(target_endian = "big") {
2282 #[doc = concat!(" ", $be_bytes)]
2284 #[doc = concat!(" ", $le_bytes)]
2288 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2289 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2290 #[must_use = "this returns the result of the operation, \
2291 without modifying the original"]
2292 // SAFETY: const sound because integers are plain old datatypes so we can always
2293 // transmute them to arrays of bytes
2295 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2296 // SAFETY: integers are plain old datatypes so we can always transmute them to
2298 unsafe { mem::transmute(self) }
2301 /// Create a native endian integer value from its representation
2302 /// as a byte array in big endian.
2304 #[doc = $from_xe_bytes_doc]
2309 #[doc = concat!("let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");")]
2310 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2313 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2316 /// use std::convert::TryInto;
2318 #[doc = concat!("fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2319 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2321 #[doc = concat!(" ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())")]
2324 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2325 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2328 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2329 Self::from_be(Self::from_ne_bytes(bytes))
2332 /// Create a native endian integer value from its representation
2333 /// as a byte array in little endian.
2335 #[doc = $from_xe_bytes_doc]
2340 #[doc = concat!("let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");")]
2341 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2344 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2347 /// use std::convert::TryInto;
2349 #[doc = concat!("fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2350 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2352 #[doc = concat!(" ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())")]
2355 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2356 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2359 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2360 Self::from_le(Self::from_ne_bytes(bytes))
2363 /// Create a native endian integer value from its memory representation
2364 /// as a byte array in native endianness.
2366 /// As the target platform's native endianness is used, portable code
2367 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2368 /// appropriate instead.
2370 /// [`from_be_bytes`]: Self::from_be_bytes
2371 /// [`from_le_bytes`]: Self::from_le_bytes
2373 #[doc = $from_xe_bytes_doc]
2378 #[doc = concat!("let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {")]
2379 #[doc = concat!(" ", $be_bytes, "")]
2381 #[doc = concat!(" ", $le_bytes, "")]
2383 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2386 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2389 /// use std::convert::TryInto;
2391 #[doc = concat!("fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2392 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2394 #[doc = concat!(" ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())")]
2397 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2398 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2400 // SAFETY: const sound because integers are plain old datatypes so we can always
2401 // transmute to them
2403 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2404 // SAFETY: integers are plain old datatypes so we can always transmute to them
2405 unsafe { mem::transmute(bytes) }
2408 /// New code should prefer to use
2409 #[doc = concat!("[`", stringify!($SelfT), "::MIN", "`] instead.")]
2411 /// Returns the smallest value that can be represented by this integer type.
2412 #[stable(feature = "rust1", since = "1.0.0")]
2415 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2416 #[rustc_deprecated(since = "TBD", reason = "replaced by the `MIN` associated constant on this type")]
2417 pub const fn min_value() -> Self { Self::MIN }
2419 /// New code should prefer to use
2420 #[doc = concat!("[`", stringify!($SelfT), "::MAX", "`] instead.")]
2422 /// Returns the largest value that can be represented by this integer type.
2423 #[stable(feature = "rust1", since = "1.0.0")]
2426 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2427 #[rustc_deprecated(since = "TBD", reason = "replaced by the `MAX` associated constant on this type")]
2428 pub const fn max_value() -> Self { Self::MAX }