core/num/
uint_macros.rs

1macro_rules! uint_impl {
2    (
3        Self = $SelfT:ty,
4        ActualT = $ActualT:ident,
5        SignedT = $SignedT:ident,
6
7        // These are all for use *only* in doc comments.
8        // As such, they're all passed as literals -- passing them as a string
9        // literal is fine if they need to be multiple code tokens.
10        // In non-comments, use the associated constants rather than these.
11        BITS = $BITS:literal,
12        BITS_MINUS_ONE = $BITS_MINUS_ONE:literal,
13        MAX = $MaxV:literal,
14        rot = $rot:literal,
15        rot_op = $rot_op:literal,
16        rot_result = $rot_result:literal,
17        swap_op = $swap_op:literal,
18        swapped = $swapped:literal,
19        reversed = $reversed:literal,
20        le_bytes = $le_bytes:literal,
21        be_bytes = $be_bytes:literal,
22        to_xe_bytes_doc = $to_xe_bytes_doc:expr,
23        from_xe_bytes_doc = $from_xe_bytes_doc:expr,
24        bound_condition = $bound_condition:literal,
25    ) => {
26        /// The smallest value that can be represented by this integer type.
27        ///
28        /// # Examples
29        ///
30        /// Basic usage:
31        ///
32        /// ```
33        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN, 0);")]
34        /// ```
35        #[stable(feature = "assoc_int_consts", since = "1.43.0")]
36        pub const MIN: Self = 0;
37
38        /// The largest value that can be represented by this integer type
39        #[doc = concat!("(2<sup>", $BITS, "</sup> &minus; 1", $bound_condition, ").")]
40        ///
41        /// # Examples
42        ///
43        /// Basic usage:
44        ///
45        /// ```
46        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($MaxV), ");")]
47        /// ```
48        #[stable(feature = "assoc_int_consts", since = "1.43.0")]
49        pub const MAX: Self = !0;
50
51        /// The size of this integer type in bits.
52        ///
53        /// # Examples
54        ///
55        /// ```
56        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::BITS, ", stringify!($BITS), ");")]
57        /// ```
58        #[stable(feature = "int_bits_const", since = "1.53.0")]
59        pub const BITS: u32 = Self::MAX.count_ones();
60
61        /// Returns the number of ones in the binary representation of `self`.
62        ///
63        /// # Examples
64        ///
65        /// Basic usage:
66        ///
67        /// ```
68        #[doc = concat!("let n = 0b01001100", stringify!($SelfT), ";")]
69        /// assert_eq!(n.count_ones(), 3);
70        ///
71        #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")]
72        #[doc = concat!("assert_eq!(max.count_ones(), ", stringify!($BITS), ");")]
73        ///
74        #[doc = concat!("let zero = 0", stringify!($SelfT), ";")]
75        /// assert_eq!(zero.count_ones(), 0);
76        /// ```
77        #[stable(feature = "rust1", since = "1.0.0")]
78        #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
79        #[doc(alias = "popcount")]
80        #[doc(alias = "popcnt")]
81        #[must_use = "this returns the result of the operation, \
82                      without modifying the original"]
83        #[inline(always)]
84        pub const fn count_ones(self) -> u32 {
85            return intrinsics::ctpop(self);
86        }
87
88        /// Returns the number of zeros in the binary representation of `self`.
89        ///
90        /// # Examples
91        ///
92        /// Basic usage:
93        ///
94        /// ```
95        #[doc = concat!("let zero = 0", stringify!($SelfT), ";")]
96        #[doc = concat!("assert_eq!(zero.count_zeros(), ", stringify!($BITS), ");")]
97        ///
98        #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")]
99        /// assert_eq!(max.count_zeros(), 0);
100        /// ```
101        #[stable(feature = "rust1", since = "1.0.0")]
102        #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
103        #[must_use = "this returns the result of the operation, \
104                      without modifying the original"]
105        #[inline(always)]
106        pub const fn count_zeros(self) -> u32 {
107            (!self).count_ones()
108        }
109
110        /// Returns the number of leading zeros in the binary representation of `self`.
111        ///
112        /// Depending on what you're doing with the value, you might also be interested in the
113        /// [`ilog2`] function which returns a consistent number, even if the type widens.
114        ///
115        /// # Examples
116        ///
117        /// Basic usage:
118        ///
119        /// ```
120        #[doc = concat!("let n = ", stringify!($SelfT), "::MAX >> 2;")]
121        /// assert_eq!(n.leading_zeros(), 2);
122        ///
123        #[doc = concat!("let zero = 0", stringify!($SelfT), ";")]
124        #[doc = concat!("assert_eq!(zero.leading_zeros(), ", stringify!($BITS), ");")]
125        ///
126        #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")]
127        /// assert_eq!(max.leading_zeros(), 0);
128        /// ```
129        #[doc = concat!("[`ilog2`]: ", stringify!($SelfT), "::ilog2")]
130        #[stable(feature = "rust1", since = "1.0.0")]
131        #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
132        #[must_use = "this returns the result of the operation, \
133                      without modifying the original"]
134        #[inline(always)]
135        pub const fn leading_zeros(self) -> u32 {
136            return intrinsics::ctlz(self as $ActualT);
137        }
138
139        /// Returns the number of trailing zeros in the binary representation
140        /// of `self`.
141        ///
142        /// # Examples
143        ///
144        /// Basic usage:
145        ///
146        /// ```
147        #[doc = concat!("let n = 0b0101000", stringify!($SelfT), ";")]
148        /// assert_eq!(n.trailing_zeros(), 3);
149        ///
150        #[doc = concat!("let zero = 0", stringify!($SelfT), ";")]
151        #[doc = concat!("assert_eq!(zero.trailing_zeros(), ", stringify!($BITS), ");")]
152        ///
153        #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")]
154        #[doc = concat!("assert_eq!(max.trailing_zeros(), 0);")]
155        /// ```
156        #[stable(feature = "rust1", since = "1.0.0")]
157        #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
158        #[must_use = "this returns the result of the operation, \
159                      without modifying the original"]
160        #[inline(always)]
161        pub const fn trailing_zeros(self) -> u32 {
162            return intrinsics::cttz(self);
163        }
164
165        /// Returns the number of leading ones in the binary representation of `self`.
166        ///
167        /// # Examples
168        ///
169        /// Basic usage:
170        ///
171        /// ```
172        #[doc = concat!("let n = !(", stringify!($SelfT), "::MAX >> 2);")]
173        /// assert_eq!(n.leading_ones(), 2);
174        ///
175        #[doc = concat!("let zero = 0", stringify!($SelfT), ";")]
176        /// assert_eq!(zero.leading_ones(), 0);
177        ///
178        #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")]
179        #[doc = concat!("assert_eq!(max.leading_ones(), ", stringify!($BITS), ");")]
180        /// ```
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"]
185        #[inline(always)]
186        pub const fn leading_ones(self) -> u32 {
187            (!self).leading_zeros()
188        }
189
190        /// Returns the number of trailing ones in the binary representation
191        /// of `self`.
192        ///
193        /// # Examples
194        ///
195        /// Basic usage:
196        ///
197        /// ```
198        #[doc = concat!("let n = 0b1010111", stringify!($SelfT), ";")]
199        /// assert_eq!(n.trailing_ones(), 3);
200        ///
201        #[doc = concat!("let zero = 0", stringify!($SelfT), ";")]
202        /// assert_eq!(zero.trailing_ones(), 0);
203        ///
204        #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")]
205        #[doc = concat!("assert_eq!(max.trailing_ones(), ", stringify!($BITS), ");")]
206        /// ```
207        #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
208        #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
209        #[must_use = "this returns the result of the operation, \
210                      without modifying the original"]
211        #[inline(always)]
212        pub const fn trailing_ones(self) -> u32 {
213            (!self).trailing_zeros()
214        }
215
216        /// Returns `self` with only the most significant bit set, or `0` if
217        /// the input is `0`.
218        ///
219        /// # Examples
220        ///
221        /// Basic usage:
222        ///
223        /// ```
224        /// #![feature(isolate_most_least_significant_one)]
225        ///
226        #[doc = concat!("let n: ", stringify!($SelfT), " = 0b_01100100;")]
227        ///
228        /// assert_eq!(n.isolate_most_significant_one(), 0b_01000000);
229        #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".isolate_most_significant_one(), 0);")]
230        /// ```
231        #[unstable(feature = "isolate_most_least_significant_one", issue = "136909")]
232        #[must_use = "this returns the result of the operation, \
233                      without modifying the original"]
234        #[inline(always)]
235        pub const fn isolate_most_significant_one(self) -> Self {
236            self & (((1 as $SelfT) << (<$SelfT>::BITS - 1)).wrapping_shr(self.leading_zeros()))
237        }
238
239        /// Returns `self` with only the least significant bit set, or `0` if
240        /// the input is `0`.
241        ///
242        /// # Examples
243        ///
244        /// Basic usage:
245        ///
246        /// ```
247        /// #![feature(isolate_most_least_significant_one)]
248        ///
249        #[doc = concat!("let n: ", stringify!($SelfT), " = 0b_01100100;")]
250        ///
251        /// assert_eq!(n.isolate_least_significant_one(), 0b_00000100);
252        #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".isolate_least_significant_one(), 0);")]
253        /// ```
254        #[unstable(feature = "isolate_most_least_significant_one", issue = "136909")]
255        #[must_use = "this returns the result of the operation, \
256                      without modifying the original"]
257        #[inline(always)]
258        pub const fn isolate_least_significant_one(self) -> Self {
259            self & self.wrapping_neg()
260        }
261
262        /// Returns the bit pattern of `self` reinterpreted as a signed integer of the same size.
263        ///
264        /// This produces the same result as an `as` cast, but ensures that the bit-width remains
265        /// the same.
266        ///
267        /// # Examples
268        ///
269        /// Basic usage:
270        ///
271        /// ```
272        #[doc = concat!("let n = ", stringify!($SelfT), "::MAX;")]
273        ///
274        #[doc = concat!("assert_eq!(n.cast_signed(), -1", stringify!($SignedT), ");")]
275        /// ```
276        #[stable(feature = "integer_sign_cast", since = "CURRENT_RUSTC_VERSION")]
277        #[rustc_const_stable(feature = "integer_sign_cast", since = "CURRENT_RUSTC_VERSION")]
278        #[must_use = "this returns the result of the operation, \
279                      without modifying the original"]
280        #[inline(always)]
281        pub const fn cast_signed(self) -> $SignedT {
282            self as $SignedT
283        }
284
285        /// Shifts the bits to the left by a specified amount, `n`,
286        /// wrapping the truncated bits to the end of the resulting integer.
287        ///
288        /// Please note this isn't the same operation as the `<<` shifting operator!
289        ///
290        /// # Examples
291        ///
292        /// Basic usage:
293        ///
294        /// ```
295        #[doc = concat!("let n = ", $rot_op, stringify!($SelfT), ";")]
296        #[doc = concat!("let m = ", $rot_result, ";")]
297        ///
298        #[doc = concat!("assert_eq!(n.rotate_left(", $rot, "), m);")]
299        /// ```
300        #[stable(feature = "rust1", since = "1.0.0")]
301        #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
302        #[must_use = "this returns the result of the operation, \
303                      without modifying the original"]
304        #[inline(always)]
305        pub const fn rotate_left(self, n: u32) -> Self {
306            return intrinsics::rotate_left(self, n);
307        }
308
309        /// Shifts the bits to the right by a specified amount, `n`,
310        /// wrapping the truncated bits to the beginning of the resulting
311        /// integer.
312        ///
313        /// Please note this isn't the same operation as the `>>` shifting operator!
314        ///
315        /// # Examples
316        ///
317        /// Basic usage:
318        ///
319        /// ```
320        #[doc = concat!("let n = ", $rot_result, stringify!($SelfT), ";")]
321        #[doc = concat!("let m = ", $rot_op, ";")]
322        ///
323        #[doc = concat!("assert_eq!(n.rotate_right(", $rot, "), m);")]
324        /// ```
325        #[stable(feature = "rust1", since = "1.0.0")]
326        #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
327        #[must_use = "this returns the result of the operation, \
328                      without modifying the original"]
329        #[inline(always)]
330        pub const fn rotate_right(self, n: u32) -> Self {
331            return intrinsics::rotate_right(self, n);
332        }
333
334        /// Reverses the byte order of the integer.
335        ///
336        /// # Examples
337        ///
338        /// Basic usage:
339        ///
340        /// ```
341        #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
342        /// let m = n.swap_bytes();
343        ///
344        #[doc = concat!("assert_eq!(m, ", $swapped, ");")]
345        /// ```
346        #[stable(feature = "rust1", since = "1.0.0")]
347        #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
348        #[must_use = "this returns the result of the operation, \
349                      without modifying the original"]
350        #[inline(always)]
351        pub const fn swap_bytes(self) -> Self {
352            intrinsics::bswap(self as $ActualT) as Self
353        }
354
355        /// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
356        ///                 second least-significant bit becomes second most-significant bit, etc.
357        ///
358        /// # Examples
359        ///
360        /// Basic usage:
361        ///
362        /// ```
363        #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
364        /// let m = n.reverse_bits();
365        ///
366        #[doc = concat!("assert_eq!(m, ", $reversed, ");")]
367        #[doc = concat!("assert_eq!(0, 0", stringify!($SelfT), ".reverse_bits());")]
368        /// ```
369        #[stable(feature = "reverse_bits", since = "1.37.0")]
370        #[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
371        #[must_use = "this returns the result of the operation, \
372                      without modifying the original"]
373        #[inline(always)]
374        pub const fn reverse_bits(self) -> Self {
375            intrinsics::bitreverse(self as $ActualT) as Self
376        }
377
378        /// Converts an integer from big endian to the target's endianness.
379        ///
380        /// On big endian this is a no-op. On little endian the bytes are
381        /// swapped.
382        ///
383        /// # Examples
384        ///
385        /// Basic usage:
386        ///
387        /// ```
388        #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
389        ///
390        /// if cfg!(target_endian = "big") {
391        #[doc = concat!("    assert_eq!(", stringify!($SelfT), "::from_be(n), n)")]
392        /// } else {
393        #[doc = concat!("    assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())")]
394        /// }
395        /// ```
396        #[stable(feature = "rust1", since = "1.0.0")]
397        #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
398        #[must_use]
399        #[inline(always)]
400        pub const fn from_be(x: Self) -> Self {
401            #[cfg(target_endian = "big")]
402            {
403                x
404            }
405            #[cfg(not(target_endian = "big"))]
406            {
407                x.swap_bytes()
408            }
409        }
410
411        /// Converts an integer from little endian to the target's endianness.
412        ///
413        /// On little endian this is a no-op. On big endian the bytes are
414        /// swapped.
415        ///
416        /// # Examples
417        ///
418        /// Basic usage:
419        ///
420        /// ```
421        #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
422        ///
423        /// if cfg!(target_endian = "little") {
424        #[doc = concat!("    assert_eq!(", stringify!($SelfT), "::from_le(n), n)")]
425        /// } else {
426        #[doc = concat!("    assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())")]
427        /// }
428        /// ```
429        #[stable(feature = "rust1", since = "1.0.0")]
430        #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
431        #[must_use]
432        #[inline(always)]
433        pub const fn from_le(x: Self) -> Self {
434            #[cfg(target_endian = "little")]
435            {
436                x
437            }
438            #[cfg(not(target_endian = "little"))]
439            {
440                x.swap_bytes()
441            }
442        }
443
444        /// Converts `self` to big endian from the target's endianness.
445        ///
446        /// On big endian this is a no-op. On little endian the bytes are
447        /// swapped.
448        ///
449        /// # Examples
450        ///
451        /// Basic usage:
452        ///
453        /// ```
454        #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
455        ///
456        /// if cfg!(target_endian = "big") {
457        ///     assert_eq!(n.to_be(), n)
458        /// } else {
459        ///     assert_eq!(n.to_be(), n.swap_bytes())
460        /// }
461        /// ```
462        #[stable(feature = "rust1", since = "1.0.0")]
463        #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
464        #[must_use = "this returns the result of the operation, \
465                      without modifying the original"]
466        #[inline(always)]
467        pub const fn to_be(self) -> Self { // or not to be?
468            #[cfg(target_endian = "big")]
469            {
470                self
471            }
472            #[cfg(not(target_endian = "big"))]
473            {
474                self.swap_bytes()
475            }
476        }
477
478        /// Converts `self` to little endian from the target's endianness.
479        ///
480        /// On little endian this is a no-op. On big endian the bytes are
481        /// swapped.
482        ///
483        /// # Examples
484        ///
485        /// Basic usage:
486        ///
487        /// ```
488        #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
489        ///
490        /// if cfg!(target_endian = "little") {
491        ///     assert_eq!(n.to_le(), n)
492        /// } else {
493        ///     assert_eq!(n.to_le(), n.swap_bytes())
494        /// }
495        /// ```
496        #[stable(feature = "rust1", since = "1.0.0")]
497        #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
498        #[must_use = "this returns the result of the operation, \
499                      without modifying the original"]
500        #[inline(always)]
501        pub const fn to_le(self) -> Self {
502            #[cfg(target_endian = "little")]
503            {
504                self
505            }
506            #[cfg(not(target_endian = "little"))]
507            {
508                self.swap_bytes()
509            }
510        }
511
512        /// Checked integer addition. Computes `self + rhs`, returning `None`
513        /// if overflow occurred.
514        ///
515        /// # Examples
516        ///
517        /// Basic usage:
518        ///
519        /// ```
520        #[doc = concat!(
521            "assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(1), ",
522            "Some(", stringify!($SelfT), "::MAX - 1));"
523        )]
524        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);")]
525        /// ```
526        #[stable(feature = "rust1", since = "1.0.0")]
527        #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
528        #[must_use = "this returns the result of the operation, \
529                      without modifying the original"]
530        #[inline]
531        pub const fn checked_add(self, rhs: Self) -> Option<Self> {
532            // This used to use `overflowing_add`, but that means it ends up being
533            // a `wrapping_add`, losing some optimization opportunities. Notably,
534            // phrasing it this way helps `.checked_add(1)` optimize to a check
535            // against `MAX` and a `add nuw`.
536            // Per <https://github.com/rust-lang/rust/pull/124114#issuecomment-2066173305>,
537            // LLVM is happy to re-form the intrinsic later if useful.
538
539            if intrinsics::unlikely(intrinsics::add_with_overflow(self, rhs).1) {
540                None
541            } else {
542                // SAFETY: Just checked it doesn't overflow
543                Some(unsafe { intrinsics::unchecked_add(self, rhs) })
544            }
545        }
546
547        /// Strict integer addition. Computes `self + rhs`, panicking
548        /// if overflow occurred.
549        ///
550        /// # Panics
551        ///
552        /// ## Overflow behavior
553        ///
554        /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
555        ///
556        /// # Examples
557        ///
558        /// Basic usage:
559        ///
560        /// ```
561        /// #![feature(strict_overflow_ops)]
562        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).strict_add(1), ", stringify!($SelfT), "::MAX - 1);")]
563        /// ```
564        ///
565        /// The following panics because of overflow:
566        ///
567        /// ```should_panic
568        /// #![feature(strict_overflow_ops)]
569        #[doc = concat!("let _ = (", stringify!($SelfT), "::MAX - 2).strict_add(3);")]
570        /// ```
571        #[unstable(feature = "strict_overflow_ops", issue = "118260")]
572        #[must_use = "this returns the result of the operation, \
573                      without modifying the original"]
574        #[inline]
575        #[track_caller]
576        pub const fn strict_add(self, rhs: Self) -> Self {
577            let (a, b) = self.overflowing_add(rhs);
578            if b { overflow_panic::add() } else { a }
579         }
580
581        /// Unchecked integer addition. Computes `self + rhs`, assuming overflow
582        /// cannot occur.
583        ///
584        /// Calling `x.unchecked_add(y)` is semantically equivalent to calling
585        /// `x.`[`checked_add`]`(y).`[`unwrap_unchecked`]`()`.
586        ///
587        /// If you're just trying to avoid the panic in debug mode, then **do not**
588        /// use this.  Instead, you're looking for [`wrapping_add`].
589        ///
590        /// # Safety
591        ///
592        /// This results in undefined behavior when
593        #[doc = concat!("`self + rhs > ", stringify!($SelfT), "::MAX` or `self + rhs < ", stringify!($SelfT), "::MIN`,")]
594        /// i.e. when [`checked_add`] would return `None`.
595        ///
596        /// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
597        #[doc = concat!("[`checked_add`]: ", stringify!($SelfT), "::checked_add")]
598        #[doc = concat!("[`wrapping_add`]: ", stringify!($SelfT), "::wrapping_add")]
599        #[stable(feature = "unchecked_math", since = "1.79.0")]
600        #[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
601        #[must_use = "this returns the result of the operation, \
602                      without modifying the original"]
603        #[inline(always)]
604        #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
605        pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
606            assert_unsafe_precondition!(
607                check_language_ub,
608                concat!(stringify!($SelfT), "::unchecked_add cannot overflow"),
609                (
610                    lhs: $SelfT = self,
611                    rhs: $SelfT = rhs,
612                ) => !lhs.overflowing_add(rhs).1,
613            );
614
615            // SAFETY: this is guaranteed to be safe by the caller.
616            unsafe {
617                intrinsics::unchecked_add(self, rhs)
618            }
619        }
620
621        /// Checked addition with a signed integer. Computes `self + rhs`,
622        /// returning `None` if overflow occurred.
623        ///
624        /// # Examples
625        ///
626        /// Basic usage:
627        ///
628        /// ```
629        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_add_signed(2), Some(3));")]
630        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_add_signed(-2), None);")]
631        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add_signed(3), None);")]
632        /// ```
633        #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
634        #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
635        #[must_use = "this returns the result of the operation, \
636                      without modifying the original"]
637        #[inline]
638        pub const fn checked_add_signed(self, rhs: $SignedT) -> Option<Self> {
639            let (a, b) = self.overflowing_add_signed(rhs);
640            if intrinsics::unlikely(b) { None } else { Some(a) }
641        }
642
643        /// Strict addition with a signed integer. Computes `self + rhs`,
644        /// panicking if overflow occurred.
645        ///
646        /// # Panics
647        ///
648        /// ## Overflow behavior
649        ///
650        /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
651        ///
652        /// # Examples
653        ///
654        /// Basic usage:
655        ///
656        /// ```
657        /// #![feature(strict_overflow_ops)]
658        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".strict_add_signed(2), 3);")]
659        /// ```
660        ///
661        /// The following panic because of overflow:
662        ///
663        /// ```should_panic
664        /// #![feature(strict_overflow_ops)]
665        #[doc = concat!("let _ = 1", stringify!($SelfT), ".strict_add_signed(-2);")]
666        /// ```
667        ///
668        /// ```should_panic
669        /// #![feature(strict_overflow_ops)]
670        #[doc = concat!("let _ = (", stringify!($SelfT), "::MAX - 2).strict_add_signed(3);")]
671        /// ```
672        #[unstable(feature = "strict_overflow_ops", issue = "118260")]
673        #[must_use = "this returns the result of the operation, \
674                      without modifying the original"]
675        #[inline]
676        #[track_caller]
677        pub const fn strict_add_signed(self, rhs: $SignedT) -> Self {
678            let (a, b) = self.overflowing_add_signed(rhs);
679            if b { overflow_panic::add() } else { a }
680         }
681
682        /// Checked integer subtraction. Computes `self - rhs`, returning
683        /// `None` if overflow occurred.
684        ///
685        /// # Examples
686        ///
687        /// Basic usage:
688        ///
689        /// ```
690        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));")]
691        #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);")]
692        /// ```
693        #[stable(feature = "rust1", since = "1.0.0")]
694        #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
695        #[must_use = "this returns the result of the operation, \
696                      without modifying the original"]
697        #[inline]
698        pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
699            // Per PR#103299, there's no advantage to the `overflowing` intrinsic
700            // for *unsigned* subtraction and we just emit the manual check anyway.
701            // Thus, rather than using `overflowing_sub` that produces a wrapping
702            // subtraction, check it ourself so we can use an unchecked one.
703
704            if self < rhs {
705                None
706            } else {
707                // SAFETY: just checked this can't overflow
708                Some(unsafe { intrinsics::unchecked_sub(self, rhs) })
709            }
710        }
711
712        /// Strict integer subtraction. Computes `self - rhs`, panicking if
713        /// overflow occurred.
714        ///
715        /// # Panics
716        ///
717        /// ## Overflow behavior
718        ///
719        /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
720        ///
721        /// # Examples
722        ///
723        /// Basic usage:
724        ///
725        /// ```
726        /// #![feature(strict_overflow_ops)]
727        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".strict_sub(1), 0);")]
728        /// ```
729        ///
730        /// The following panics because of overflow:
731        ///
732        /// ```should_panic
733        /// #![feature(strict_overflow_ops)]
734        #[doc = concat!("let _ = 0", stringify!($SelfT), ".strict_sub(1);")]
735        /// ```
736        #[unstable(feature = "strict_overflow_ops", issue = "118260")]
737        #[must_use = "this returns the result of the operation, \
738                      without modifying the original"]
739        #[inline]
740        #[track_caller]
741        pub const fn strict_sub(self, rhs: Self) -> Self {
742            let (a, b) = self.overflowing_sub(rhs);
743            if b { overflow_panic::sub() } else { a }
744         }
745
746        /// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
747        /// cannot occur.
748        ///
749        /// Calling `x.unchecked_sub(y)` is semantically equivalent to calling
750        /// `x.`[`checked_sub`]`(y).`[`unwrap_unchecked`]`()`.
751        ///
752        /// If you're just trying to avoid the panic in debug mode, then **do not**
753        /// use this.  Instead, you're looking for [`wrapping_sub`].
754        ///
755        /// If you find yourself writing code like this:
756        ///
757        /// ```
758        /// # let foo = 30_u32;
759        /// # let bar = 20;
760        /// if foo >= bar {
761        ///     // SAFETY: just checked it will not overflow
762        ///     let diff = unsafe { foo.unchecked_sub(bar) };
763        ///     // ... use diff ...
764        /// }
765        /// ```
766        ///
767        /// Consider changing it to
768        ///
769        /// ```
770        /// # let foo = 30_u32;
771        /// # let bar = 20;
772        /// if let Some(diff) = foo.checked_sub(bar) {
773        ///     // ... use diff ...
774        /// }
775        /// ```
776        ///
777        /// As that does exactly the same thing -- including telling the optimizer
778        /// that the subtraction cannot overflow -- but avoids needing `unsafe`.
779        ///
780        /// # Safety
781        ///
782        /// This results in undefined behavior when
783        #[doc = concat!("`self - rhs > ", stringify!($SelfT), "::MAX` or `self - rhs < ", stringify!($SelfT), "::MIN`,")]
784        /// i.e. when [`checked_sub`] would return `None`.
785        ///
786        /// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
787        #[doc = concat!("[`checked_sub`]: ", stringify!($SelfT), "::checked_sub")]
788        #[doc = concat!("[`wrapping_sub`]: ", stringify!($SelfT), "::wrapping_sub")]
789        #[stable(feature = "unchecked_math", since = "1.79.0")]
790        #[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
791        #[must_use = "this returns the result of the operation, \
792                      without modifying the original"]
793        #[inline(always)]
794        #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
795        pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
796            assert_unsafe_precondition!(
797                check_language_ub,
798                concat!(stringify!($SelfT), "::unchecked_sub cannot overflow"),
799                (
800                    lhs: $SelfT = self,
801                    rhs: $SelfT = rhs,
802                ) => !lhs.overflowing_sub(rhs).1,
803            );
804
805            // SAFETY: this is guaranteed to be safe by the caller.
806            unsafe {
807                intrinsics::unchecked_sub(self, rhs)
808            }
809        }
810
811        /// Checked subtraction with a signed integer. Computes `self - rhs`,
812        /// returning `None` if overflow occurred.
813        ///
814        /// # Examples
815        ///
816        /// Basic usage:
817        ///
818        /// ```
819        /// #![feature(mixed_integer_ops_unsigned_sub)]
820        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_sub_signed(2), None);")]
821        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_sub_signed(-2), Some(3));")]
822        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_sub_signed(-4), None);")]
823        /// ```
824        #[unstable(feature = "mixed_integer_ops_unsigned_sub", issue = "126043")]
825        #[must_use = "this returns the result of the operation, \
826                      without modifying the original"]
827        #[inline]
828        pub const fn checked_sub_signed(self, rhs: $SignedT) -> Option<Self> {
829            let (res, overflow) = self.overflowing_sub_signed(rhs);
830
831            if !overflow {
832                Some(res)
833            } else {
834                None
835            }
836        }
837
838        #[doc = concat!(
839            "Checked integer subtraction. Computes `self - rhs` and checks if the result fits into an [`",
840            stringify!($SignedT), "`], returning `None` if overflow occurred."
841        )]
842        ///
843        /// # Examples
844        ///
845        /// Basic usage:
846        ///
847        /// ```
848        /// #![feature(unsigned_signed_diff)]
849        #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_signed_diff(2), Some(8));")]
850        #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_signed_diff(10), Some(-8));")]
851        #[doc = concat!(
852            "assert_eq!(",
853            stringify!($SelfT),
854            "::MAX.checked_signed_diff(",
855            stringify!($SignedT),
856            "::MAX as ",
857            stringify!($SelfT),
858            "), None);"
859        )]
860        #[doc = concat!(
861            "assert_eq!((",
862            stringify!($SignedT),
863            "::MAX as ",
864            stringify!($SelfT),
865            ").checked_signed_diff(",
866            stringify!($SelfT),
867            "::MAX), Some(",
868            stringify!($SignedT),
869            "::MIN));"
870        )]
871        #[doc = concat!(
872            "assert_eq!((",
873            stringify!($SignedT),
874            "::MAX as ",
875            stringify!($SelfT),
876            " + 1).checked_signed_diff(0), None);"
877        )]
878        #[doc = concat!(
879            "assert_eq!(",
880            stringify!($SelfT),
881            "::MAX.checked_signed_diff(",
882            stringify!($SelfT),
883            "::MAX), Some(0));"
884        )]
885        /// ```
886        #[unstable(feature = "unsigned_signed_diff", issue = "126041")]
887        #[inline]
888        pub const fn checked_signed_diff(self, rhs: Self) -> Option<$SignedT> {
889            let res = self.wrapping_sub(rhs) as $SignedT;
890            let overflow = (self >= rhs) == (res < 0);
891
892            if !overflow {
893                Some(res)
894            } else {
895                None
896            }
897        }
898
899        /// Checked integer multiplication. Computes `self * rhs`, returning
900        /// `None` if overflow occurred.
901        ///
902        /// # Examples
903        ///
904        /// Basic usage:
905        ///
906        /// ```
907        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));")]
908        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);")]
909        /// ```
910        #[stable(feature = "rust1", since = "1.0.0")]
911        #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
912        #[must_use = "this returns the result of the operation, \
913                      without modifying the original"]
914        #[inline]
915        pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
916            let (a, b) = self.overflowing_mul(rhs);
917            if intrinsics::unlikely(b) { None } else { Some(a) }
918        }
919
920        /// Strict integer multiplication. Computes `self * rhs`, panicking if
921        /// overflow occurred.
922        ///
923        /// # Panics
924        ///
925        /// ## Overflow behavior
926        ///
927        /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
928        ///
929        /// # Examples
930        ///
931        /// Basic usage:
932        ///
933        /// ```
934        /// #![feature(strict_overflow_ops)]
935        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".strict_mul(1), 5);")]
936        /// ```
937        ///
938        /// The following panics because of overflow:
939        ///
940        /// ``` should_panic
941        /// #![feature(strict_overflow_ops)]
942        #[doc = concat!("let _ = ", stringify!($SelfT), "::MAX.strict_mul(2);")]
943        /// ```
944        #[unstable(feature = "strict_overflow_ops", issue = "118260")]
945        #[must_use = "this returns the result of the operation, \
946                      without modifying the original"]
947        #[inline]
948        #[track_caller]
949        pub const fn strict_mul(self, rhs: Self) -> Self {
950            let (a, b) = self.overflowing_mul(rhs);
951            if b { overflow_panic::mul() } else { a }
952         }
953
954        /// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
955        /// cannot occur.
956        ///
957        /// Calling `x.unchecked_mul(y)` is semantically equivalent to calling
958        /// `x.`[`checked_mul`]`(y).`[`unwrap_unchecked`]`()`.
959        ///
960        /// If you're just trying to avoid the panic in debug mode, then **do not**
961        /// use this.  Instead, you're looking for [`wrapping_mul`].
962        ///
963        /// # Safety
964        ///
965        /// This results in undefined behavior when
966        #[doc = concat!("`self * rhs > ", stringify!($SelfT), "::MAX` or `self * rhs < ", stringify!($SelfT), "::MIN`,")]
967        /// i.e. when [`checked_mul`] would return `None`.
968        ///
969        /// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
970        #[doc = concat!("[`checked_mul`]: ", stringify!($SelfT), "::checked_mul")]
971        #[doc = concat!("[`wrapping_mul`]: ", stringify!($SelfT), "::wrapping_mul")]
972        #[stable(feature = "unchecked_math", since = "1.79.0")]
973        #[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
974        #[must_use = "this returns the result of the operation, \
975                      without modifying the original"]
976        #[inline(always)]
977        #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
978        pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
979            assert_unsafe_precondition!(
980                check_language_ub,
981                concat!(stringify!($SelfT), "::unchecked_mul cannot overflow"),
982                (
983                    lhs: $SelfT = self,
984                    rhs: $SelfT = rhs,
985                ) => !lhs.overflowing_mul(rhs).1,
986            );
987
988            // SAFETY: this is guaranteed to be safe by the caller.
989            unsafe {
990                intrinsics::unchecked_mul(self, rhs)
991            }
992        }
993
994        /// Checked integer division. Computes `self / rhs`, returning `None`
995        /// if `rhs == 0`.
996        ///
997        /// # Examples
998        ///
999        /// Basic usage:
1000        ///
1001        /// ```
1002        #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));")]
1003        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);")]
1004        /// ```
1005        #[stable(feature = "rust1", since = "1.0.0")]
1006        #[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
1007        #[must_use = "this returns the result of the operation, \
1008                      without modifying the original"]
1009        #[inline]
1010        pub const fn checked_div(self, rhs: Self) -> Option<Self> {
1011            if intrinsics::unlikely(rhs == 0) {
1012                None
1013            } else {
1014                // SAFETY: div by zero has been checked above and unsigned types have no other
1015                // failure modes for division
1016                Some(unsafe { intrinsics::unchecked_div(self, rhs) })
1017            }
1018        }
1019
1020        /// Strict integer division. Computes `self / rhs`.
1021        ///
1022        /// Strict division on unsigned types is just normal division. There's no
1023        /// way overflow could ever happen. This function exists so that all
1024        /// operations are accounted for in the strict operations.
1025        ///
1026        /// # Panics
1027        ///
1028        /// This function will panic if `rhs` is zero.
1029        ///
1030        /// # Examples
1031        ///
1032        /// Basic usage:
1033        ///
1034        /// ```
1035        /// #![feature(strict_overflow_ops)]
1036        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".strict_div(10), 10);")]
1037        /// ```
1038        ///
1039        /// The following panics because of division by zero:
1040        ///
1041        /// ```should_panic
1042        /// #![feature(strict_overflow_ops)]
1043        #[doc = concat!("let _ = (1", stringify!($SelfT), ").strict_div(0);")]
1044        /// ```
1045        #[unstable(feature = "strict_overflow_ops", issue = "118260")]
1046        #[must_use = "this returns the result of the operation, \
1047                      without modifying the original"]
1048        #[inline(always)]
1049        #[track_caller]
1050        pub const fn strict_div(self, rhs: Self) -> Self {
1051            self / rhs
1052        }
1053
1054        /// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
1055        /// if `rhs == 0`.
1056        ///
1057        /// # Examples
1058        ///
1059        /// Basic usage:
1060        ///
1061        /// ```
1062        #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));")]
1063        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);")]
1064        /// ```
1065        #[stable(feature = "euclidean_division", since = "1.38.0")]
1066        #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1067        #[must_use = "this returns the result of the operation, \
1068                      without modifying the original"]
1069        #[inline]
1070        pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
1071            if intrinsics::unlikely(rhs == 0) {
1072                None
1073            } else {
1074                Some(self.div_euclid(rhs))
1075            }
1076        }
1077
1078        /// Strict Euclidean division. Computes `self.div_euclid(rhs)`.
1079        ///
1080        /// Strict division on unsigned types is just normal division. There's no
1081        /// way overflow could ever happen. This function exists so that all
1082        /// operations are accounted for in the strict operations. Since, for the
1083        /// positive integers, all common definitions of division are equal, this
1084        /// is exactly equal to `self.strict_div(rhs)`.
1085        ///
1086        /// # Panics
1087        ///
1088        /// This function will panic if `rhs` is zero.
1089        ///
1090        /// # Examples
1091        ///
1092        /// Basic usage:
1093        ///
1094        /// ```
1095        /// #![feature(strict_overflow_ops)]
1096        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".strict_div_euclid(10), 10);")]
1097        /// ```
1098        /// The following panics because of division by zero:
1099        ///
1100        /// ```should_panic
1101        /// #![feature(strict_overflow_ops)]
1102        #[doc = concat!("let _ = (1", stringify!($SelfT), ").strict_div_euclid(0);")]
1103        /// ```
1104        #[unstable(feature = "strict_overflow_ops", issue = "118260")]
1105        #[must_use = "this returns the result of the operation, \
1106                      without modifying the original"]
1107        #[inline(always)]
1108        #[track_caller]
1109        pub const fn strict_div_euclid(self, rhs: Self) -> Self {
1110            self / rhs
1111        }
1112
1113        /// Checked integer remainder. Computes `self % rhs`, returning `None`
1114        /// if `rhs == 0`.
1115        ///
1116        /// # Examples
1117        ///
1118        /// Basic usage:
1119        ///
1120        /// ```
1121        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));")]
1122        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);")]
1123        /// ```
1124        #[stable(feature = "wrapping", since = "1.7.0")]
1125        #[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
1126        #[must_use = "this returns the result of the operation, \
1127                      without modifying the original"]
1128        #[inline]
1129        pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
1130            if intrinsics::unlikely(rhs == 0) {
1131                None
1132            } else {
1133                // SAFETY: div by zero has been checked above and unsigned types have no other
1134                // failure modes for division
1135                Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
1136            }
1137        }
1138
1139        /// Strict integer remainder. Computes `self % rhs`.
1140        ///
1141        /// Strict remainder calculation on unsigned types is just the regular
1142        /// remainder calculation. There's no way overflow could ever happen.
1143        /// This function exists so that all operations are accounted for in the
1144        /// strict operations.
1145        ///
1146        /// # Panics
1147        ///
1148        /// This function will panic if `rhs` is zero.
1149        ///
1150        /// # Examples
1151        ///
1152        /// Basic usage:
1153        ///
1154        /// ```
1155        /// #![feature(strict_overflow_ops)]
1156        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".strict_rem(10), 0);")]
1157        /// ```
1158        ///
1159        /// The following panics because of division by zero:
1160        ///
1161        /// ```should_panic
1162        /// #![feature(strict_overflow_ops)]
1163        #[doc = concat!("let _ = 5", stringify!($SelfT), ".strict_rem(0);")]
1164        /// ```
1165        #[unstable(feature = "strict_overflow_ops", issue = "118260")]
1166        #[must_use = "this returns the result of the operation, \
1167                      without modifying the original"]
1168        #[inline(always)]
1169        #[track_caller]
1170        pub const fn strict_rem(self, rhs: Self) -> Self {
1171            self % rhs
1172        }
1173
1174        /// Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
1175        /// if `rhs == 0`.
1176        ///
1177        /// # Examples
1178        ///
1179        /// Basic usage:
1180        ///
1181        /// ```
1182        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));")]
1183        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);")]
1184        /// ```
1185        #[stable(feature = "euclidean_division", since = "1.38.0")]
1186        #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1187        #[must_use = "this returns the result of the operation, \
1188                      without modifying the original"]
1189        #[inline]
1190        pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
1191            if intrinsics::unlikely(rhs == 0) {
1192                None
1193            } else {
1194                Some(self.rem_euclid(rhs))
1195            }
1196        }
1197
1198        /// Strict Euclidean modulo. Computes `self.rem_euclid(rhs)`.
1199        ///
1200        /// Strict modulo calculation on unsigned types is just the regular
1201        /// remainder calculation. There's no way overflow could ever happen.
1202        /// This function exists so that all operations are accounted for in the
1203        /// strict operations. Since, for the positive integers, all common
1204        /// definitions of division are equal, this is exactly equal to
1205        /// `self.strict_rem(rhs)`.
1206        ///
1207        /// # Panics
1208        ///
1209        /// This function will panic if `rhs` is zero.
1210        ///
1211        /// # Examples
1212        ///
1213        /// Basic usage:
1214        ///
1215        /// ```
1216        /// #![feature(strict_overflow_ops)]
1217        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".strict_rem_euclid(10), 0);")]
1218        /// ```
1219        ///
1220        /// The following panics because of division by zero:
1221        ///
1222        /// ```should_panic
1223        /// #![feature(strict_overflow_ops)]
1224        #[doc = concat!("let _ = 5", stringify!($SelfT), ".strict_rem_euclid(0);")]
1225        /// ```
1226        #[unstable(feature = "strict_overflow_ops", issue = "118260")]
1227        #[must_use = "this returns the result of the operation, \
1228                      without modifying the original"]
1229        #[inline(always)]
1230        #[track_caller]
1231        pub const fn strict_rem_euclid(self, rhs: Self) -> Self {
1232            self % rhs
1233        }
1234
1235        /// Same value as `self | other`, but UB if any bit position is set in both inputs.
1236        ///
1237        /// This is a situational micro-optimization for places where you'd rather
1238        /// use addition on some platforms and bitwise or on other platforms, based
1239        /// on exactly which instructions combine better with whatever else you're
1240        /// doing.  Note that there's no reason to bother using this for places
1241        /// where it's clear from the operations involved that they can't overlap.
1242        /// For example, if you're combining `u16`s into a `u32` with
1243        /// `((a as u32) << 16) | (b as u32)`, that's fine, as the backend will
1244        /// know those sides of the `|` are disjoint without needing help.
1245        ///
1246        /// # Examples
1247        ///
1248        /// ```
1249        /// #![feature(disjoint_bitor)]
1250        ///
1251        /// // SAFETY: `1` and `4` have no bits in common.
1252        /// unsafe {
1253        #[doc = concat!("    assert_eq!(1_", stringify!($SelfT), ".unchecked_disjoint_bitor(4), 5);")]
1254        /// }
1255        /// ```
1256        ///
1257        /// # Safety
1258        ///
1259        /// Requires that `(self & other) == 0`, otherwise it's immediate UB.
1260        ///
1261        /// Equivalently, requires that `(self | other) == (self + other)`.
1262        #[unstable(feature = "disjoint_bitor", issue = "135758")]
1263        #[rustc_const_unstable(feature = "disjoint_bitor", issue = "135758")]
1264        #[inline]
1265        pub const unsafe fn unchecked_disjoint_bitor(self, other: Self) -> Self {
1266            assert_unsafe_precondition!(
1267                check_language_ub,
1268                concat!(stringify!($SelfT), "::unchecked_disjoint_bitor cannot have overlapping bits"),
1269                (
1270                    lhs: $SelfT = self,
1271                    rhs: $SelfT = other,
1272                ) => (lhs & rhs) == 0,
1273            );
1274
1275            // SAFETY: Same precondition
1276            unsafe { intrinsics::disjoint_bitor(self, other) }
1277        }
1278
1279        /// Returns the logarithm of the number with respect to an arbitrary base,
1280        /// rounded down.
1281        ///
1282        /// This method might not be optimized owing to implementation details;
1283        /// `ilog2` can produce results more efficiently for base 2, and `ilog10`
1284        /// can produce results more efficiently for base 10.
1285        ///
1286        /// # Panics
1287        ///
1288        /// This function will panic if `self` is zero, or if `base` is less than 2.
1289        ///
1290        /// # Examples
1291        ///
1292        /// ```
1293        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".ilog(5), 1);")]
1294        /// ```
1295        #[stable(feature = "int_log", since = "1.67.0")]
1296        #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1297        #[must_use = "this returns the result of the operation, \
1298                      without modifying the original"]
1299        #[inline]
1300        #[track_caller]
1301        pub const fn ilog(self, base: Self) -> u32 {
1302            assert!(base >= 2, "base of integer logarithm must be at least 2");
1303            if let Some(log) = self.checked_ilog(base) {
1304                log
1305            } else {
1306                int_log10::panic_for_nonpositive_argument()
1307            }
1308        }
1309
1310        /// Returns the base 2 logarithm of the number, rounded down.
1311        ///
1312        /// # Panics
1313        ///
1314        /// This function will panic if `self` is zero.
1315        ///
1316        /// # Examples
1317        ///
1318        /// ```
1319        #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".ilog2(), 1);")]
1320        /// ```
1321        #[stable(feature = "int_log", since = "1.67.0")]
1322        #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1323        #[must_use = "this returns the result of the operation, \
1324                      without modifying the original"]
1325        #[inline]
1326        #[track_caller]
1327        pub const fn ilog2(self) -> u32 {
1328            if let Some(log) = self.checked_ilog2() {
1329                log
1330            } else {
1331                int_log10::panic_for_nonpositive_argument()
1332            }
1333        }
1334
1335        /// Returns the base 10 logarithm of the number, rounded down.
1336        ///
1337        /// # Panics
1338        ///
1339        /// This function will panic if `self` is zero.
1340        ///
1341        /// # Example
1342        ///
1343        /// ```
1344        #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".ilog10(), 1);")]
1345        /// ```
1346        #[stable(feature = "int_log", since = "1.67.0")]
1347        #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1348        #[must_use = "this returns the result of the operation, \
1349                      without modifying the original"]
1350        #[inline]
1351        #[track_caller]
1352        pub const fn ilog10(self) -> u32 {
1353            if let Some(log) = self.checked_ilog10() {
1354                log
1355            } else {
1356                int_log10::panic_for_nonpositive_argument()
1357            }
1358        }
1359
1360        /// Returns the logarithm of the number with respect to an arbitrary base,
1361        /// rounded down.
1362        ///
1363        /// Returns `None` if the number is zero, or if the base is not at least 2.
1364        ///
1365        /// This method might not be optimized owing to implementation details;
1366        /// `checked_ilog2` can produce results more efficiently for base 2, and
1367        /// `checked_ilog10` can produce results more efficiently for base 10.
1368        ///
1369        /// # Examples
1370        ///
1371        /// ```
1372        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_ilog(5), Some(1));")]
1373        /// ```
1374        #[stable(feature = "int_log", since = "1.67.0")]
1375        #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1376        #[must_use = "this returns the result of the operation, \
1377                      without modifying the original"]
1378        #[inline]
1379        pub const fn checked_ilog(self, base: Self) -> Option<u32> {
1380            if self <= 0 || base <= 1 {
1381                None
1382            } else if self < base {
1383                Some(0)
1384            } else {
1385                // Since base >= self, n >= 1
1386                let mut n = 1;
1387                let mut r = base;
1388
1389                // Optimization for 128 bit wide integers.
1390                if Self::BITS == 128 {
1391                    // The following is a correct lower bound for ⌊log(base,self)⌋ because
1392                    //
1393                    // log(base,self) = log(2,self) / log(2,base)
1394                    //                ≥ ⌊log(2,self)⌋ / (⌊log(2,base)⌋ + 1)
1395                    //
1396                    // hence
1397                    //
1398                    // ⌊log(base,self)⌋ ≥ ⌊ ⌊log(2,self)⌋ / (⌊log(2,base)⌋ + 1) ⌋ .
1399                    n = self.ilog2() / (base.ilog2() + 1);
1400                    r = base.pow(n);
1401                }
1402
1403                while r <= self / base {
1404                    n += 1;
1405                    r *= base;
1406                }
1407                Some(n)
1408            }
1409        }
1410
1411        /// Returns the base 2 logarithm of the number, rounded down.
1412        ///
1413        /// Returns `None` if the number is zero.
1414        ///
1415        /// # Examples
1416        ///
1417        /// ```
1418        #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_ilog2(), Some(1));")]
1419        /// ```
1420        #[stable(feature = "int_log", since = "1.67.0")]
1421        #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1422        #[must_use = "this returns the result of the operation, \
1423                      without modifying the original"]
1424        #[inline]
1425        pub const fn checked_ilog2(self) -> Option<u32> {
1426            match NonZero::new(self) {
1427                Some(x) => Some(x.ilog2()),
1428                None => None,
1429            }
1430        }
1431
1432        /// Returns the base 10 logarithm of the number, rounded down.
1433        ///
1434        /// Returns `None` if the number is zero.
1435        ///
1436        /// # Examples
1437        ///
1438        /// ```
1439        #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_ilog10(), Some(1));")]
1440        /// ```
1441        #[stable(feature = "int_log", since = "1.67.0")]
1442        #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1443        #[must_use = "this returns the result of the operation, \
1444                      without modifying the original"]
1445        #[inline]
1446        pub const fn checked_ilog10(self) -> Option<u32> {
1447            match NonZero::new(self) {
1448                Some(x) => Some(x.ilog10()),
1449                None => None,
1450            }
1451        }
1452
1453        /// Checked negation. Computes `-self`, returning `None` unless `self ==
1454        /// 0`.
1455        ///
1456        /// Note that negating any positive integer will overflow.
1457        ///
1458        /// # Examples
1459        ///
1460        /// Basic usage:
1461        ///
1462        /// ```
1463        #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));")]
1464        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);")]
1465        /// ```
1466        #[stable(feature = "wrapping", since = "1.7.0")]
1467        #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
1468        #[must_use = "this returns the result of the operation, \
1469                      without modifying the original"]
1470        #[inline]
1471        pub const fn checked_neg(self) -> Option<Self> {
1472            let (a, b) = self.overflowing_neg();
1473            if intrinsics::unlikely(b) { None } else { Some(a) }
1474        }
1475
1476        /// Strict negation. Computes `-self`, panicking unless `self ==
1477        /// 0`.
1478        ///
1479        /// Note that negating any positive integer will overflow.
1480        ///
1481        /// # Panics
1482        ///
1483        /// ## Overflow behavior
1484        ///
1485        /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
1486        ///
1487        /// # Examples
1488        ///
1489        /// Basic usage:
1490        ///
1491        /// ```
1492        /// #![feature(strict_overflow_ops)]
1493        #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".strict_neg(), 0);")]
1494        /// ```
1495        ///
1496        /// The following panics because of overflow:
1497        ///
1498        /// ```should_panic
1499        /// #![feature(strict_overflow_ops)]
1500        #[doc = concat!("let _ = 1", stringify!($SelfT), ".strict_neg();")]
1501        ///
1502        #[unstable(feature = "strict_overflow_ops", issue = "118260")]
1503        #[must_use = "this returns the result of the operation, \
1504                      without modifying the original"]
1505        #[inline]
1506        #[track_caller]
1507        pub const fn strict_neg(self) -> Self {
1508            let (a, b) = self.overflowing_neg();
1509            if b { overflow_panic::neg() } else { a }
1510        }
1511
1512        /// Checked shift left. Computes `self << rhs`, returning `None`
1513        /// if `rhs` is larger than or equal to the number of bits in `self`.
1514        ///
1515        /// # Examples
1516        ///
1517        /// Basic usage:
1518        ///
1519        /// ```
1520        #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));")]
1521        #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);")]
1522        #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shl(", stringify!($BITS_MINUS_ONE), "), Some(0));")]
1523        /// ```
1524        #[stable(feature = "wrapping", since = "1.7.0")]
1525        #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
1526        #[must_use = "this returns the result of the operation, \
1527                      without modifying the original"]
1528        #[inline]
1529        pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
1530            // Not using overflowing_shl as that's a wrapping shift
1531            if rhs < Self::BITS {
1532                // SAFETY: just checked the RHS is in-range
1533                Some(unsafe { self.unchecked_shl(rhs) })
1534            } else {
1535                None
1536            }
1537        }
1538
1539        /// Strict shift left. Computes `self << rhs`, panicking if `rhs` is larger
1540        /// than or equal to the number of bits in `self`.
1541        ///
1542        /// # Panics
1543        ///
1544        /// ## Overflow behavior
1545        ///
1546        /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
1547        ///
1548        /// # Examples
1549        ///
1550        /// Basic usage:
1551        ///
1552        /// ```
1553        /// #![feature(strict_overflow_ops)]
1554        #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".strict_shl(4), 0x10);")]
1555        /// ```
1556        ///
1557        /// The following panics because of overflow:
1558        ///
1559        /// ```should_panic
1560        /// #![feature(strict_overflow_ops)]
1561        #[doc = concat!("let _ = 0x10", stringify!($SelfT), ".strict_shl(129);")]
1562        /// ```
1563        #[unstable(feature = "strict_overflow_ops", issue = "118260")]
1564        #[must_use = "this returns the result of the operation, \
1565                      without modifying the original"]
1566        #[inline]
1567        #[track_caller]
1568        pub const fn strict_shl(self, rhs: u32) -> Self {
1569            let (a, b) = self.overflowing_shl(rhs);
1570            if b { overflow_panic::shl() } else { a }
1571        }
1572
1573        /// Unchecked shift left. Computes `self << rhs`, assuming that
1574        /// `rhs` is less than the number of bits in `self`.
1575        ///
1576        /// # Safety
1577        ///
1578        /// This results in undefined behavior if `rhs` is larger than
1579        /// or equal to the number of bits in `self`,
1580        /// i.e. when [`checked_shl`] would return `None`.
1581        ///
1582        #[doc = concat!("[`checked_shl`]: ", stringify!($SelfT), "::checked_shl")]
1583        #[unstable(
1584            feature = "unchecked_shifts",
1585            reason = "niche optimization path",
1586            issue = "85122",
1587        )]
1588        #[must_use = "this returns the result of the operation, \
1589                      without modifying the original"]
1590        #[inline(always)]
1591        #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1592        pub const unsafe fn unchecked_shl(self, rhs: u32) -> Self {
1593            assert_unsafe_precondition!(
1594                check_language_ub,
1595                concat!(stringify!($SelfT), "::unchecked_shl cannot overflow"),
1596                (
1597                    rhs: u32 = rhs,
1598                ) => rhs < <$ActualT>::BITS,
1599            );
1600
1601            // SAFETY: this is guaranteed to be safe by the caller.
1602            unsafe {
1603                intrinsics::unchecked_shl(self, rhs)
1604            }
1605        }
1606
1607        /// Unbounded shift left. Computes `self << rhs`, without bounding the value of `rhs`.
1608        ///
1609        /// If `rhs` is larger or equal to the number of bits in `self`,
1610        /// the entire value is shifted out, and `0` is returned.
1611        ///
1612        /// # Examples
1613        ///
1614        /// Basic usage:
1615        /// ```
1616        #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".unbounded_shl(4), 0x10);")]
1617        #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".unbounded_shl(129), 0);")]
1618        /// ```
1619        #[stable(feature = "unbounded_shifts", since = "CURRENT_RUSTC_VERSION")]
1620        #[rustc_const_stable(feature = "unbounded_shifts", since = "CURRENT_RUSTC_VERSION")]
1621        #[must_use = "this returns the result of the operation, \
1622                      without modifying the original"]
1623        #[inline]
1624        pub const fn unbounded_shl(self, rhs: u32) -> $SelfT{
1625            if rhs < Self::BITS {
1626                // SAFETY:
1627                // rhs is just checked to be in-range above
1628                unsafe { self.unchecked_shl(rhs) }
1629            } else {
1630                0
1631            }
1632        }
1633
1634        /// Checked shift right. Computes `self >> rhs`, returning `None`
1635        /// if `rhs` is larger than or equal to the number of bits in `self`.
1636        ///
1637        /// # Examples
1638        ///
1639        /// Basic usage:
1640        ///
1641        /// ```
1642        #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));")]
1643        #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);")]
1644        /// ```
1645        #[stable(feature = "wrapping", since = "1.7.0")]
1646        #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
1647        #[must_use = "this returns the result of the operation, \
1648                      without modifying the original"]
1649        #[inline]
1650        pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
1651            // Not using overflowing_shr as that's a wrapping shift
1652            if rhs < Self::BITS {
1653                // SAFETY: just checked the RHS is in-range
1654                Some(unsafe { self.unchecked_shr(rhs) })
1655            } else {
1656                None
1657            }
1658        }
1659
1660        /// Strict shift right. Computes `self >> rhs`, panicking `rhs` is
1661        /// larger than or equal to the number of bits in `self`.
1662        ///
1663        /// # Panics
1664        ///
1665        /// ## Overflow behavior
1666        ///
1667        /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
1668        ///
1669        /// # Examples
1670        ///
1671        /// Basic usage:
1672        ///
1673        /// ```
1674        /// #![feature(strict_overflow_ops)]
1675        #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".strict_shr(4), 0x1);")]
1676        /// ```
1677        ///
1678        /// The following panics because of overflow:
1679        ///
1680        /// ```should_panic
1681        /// #![feature(strict_overflow_ops)]
1682        #[doc = concat!("let _ = 0x10", stringify!($SelfT), ".strict_shr(129);")]
1683        /// ```
1684        #[unstable(feature = "strict_overflow_ops", issue = "118260")]
1685        #[must_use = "this returns the result of the operation, \
1686                      without modifying the original"]
1687        #[inline]
1688        #[track_caller]
1689        pub const fn strict_shr(self, rhs: u32) -> Self {
1690            let (a, b) = self.overflowing_shr(rhs);
1691            if b { overflow_panic::shr() } else { a }
1692        }
1693
1694        /// Unchecked shift right. Computes `self >> rhs`, assuming that
1695        /// `rhs` is less than the number of bits in `self`.
1696        ///
1697        /// # Safety
1698        ///
1699        /// This results in undefined behavior if `rhs` is larger than
1700        /// or equal to the number of bits in `self`,
1701        /// i.e. when [`checked_shr`] would return `None`.
1702        ///
1703        #[doc = concat!("[`checked_shr`]: ", stringify!($SelfT), "::checked_shr")]
1704        #[unstable(
1705            feature = "unchecked_shifts",
1706            reason = "niche optimization path",
1707            issue = "85122",
1708        )]
1709        #[must_use = "this returns the result of the operation, \
1710                      without modifying the original"]
1711        #[inline(always)]
1712        #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1713        pub const unsafe fn unchecked_shr(self, rhs: u32) -> Self {
1714            assert_unsafe_precondition!(
1715                check_language_ub,
1716                concat!(stringify!($SelfT), "::unchecked_shr cannot overflow"),
1717                (
1718                    rhs: u32 = rhs,
1719                ) => rhs < <$ActualT>::BITS,
1720            );
1721
1722            // SAFETY: this is guaranteed to be safe by the caller.
1723            unsafe {
1724                intrinsics::unchecked_shr(self, rhs)
1725            }
1726        }
1727
1728        /// Unbounded shift right. Computes `self >> rhs`, without bounding the value of `rhs`.
1729        ///
1730        /// If `rhs` is larger or equal to the number of bits in `self`,
1731        /// the entire value is shifted out, and `0` is returned.
1732        ///
1733        /// # Examples
1734        ///
1735        /// Basic usage:
1736        /// ```
1737        #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".unbounded_shr(4), 0x1);")]
1738        #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".unbounded_shr(129), 0);")]
1739        /// ```
1740        #[stable(feature = "unbounded_shifts", since = "CURRENT_RUSTC_VERSION")]
1741        #[rustc_const_stable(feature = "unbounded_shifts", since = "CURRENT_RUSTC_VERSION")]
1742        #[must_use = "this returns the result of the operation, \
1743                      without modifying the original"]
1744        #[inline]
1745        pub const fn unbounded_shr(self, rhs: u32) -> $SelfT{
1746            if rhs < Self::BITS {
1747                // SAFETY:
1748                // rhs is just checked to be in-range above
1749                unsafe { self.unchecked_shr(rhs) }
1750            } else {
1751                0
1752            }
1753        }
1754
1755        /// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
1756        /// overflow occurred.
1757        ///
1758        /// # Examples
1759        ///
1760        /// Basic usage:
1761        ///
1762        /// ```
1763        #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));")]
1764        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);")]
1765        /// ```
1766        #[stable(feature = "no_panic_pow", since = "1.34.0")]
1767        #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1768        #[must_use = "this returns the result of the operation, \
1769                      without modifying the original"]
1770        #[inline]
1771        pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
1772            if exp == 0 {
1773                return Some(1);
1774            }
1775            let mut base = self;
1776            let mut acc: Self = 1;
1777
1778            loop {
1779                if (exp & 1) == 1 {
1780                    acc = try_opt!(acc.checked_mul(base));
1781                    // since exp!=0, finally the exp must be 1.
1782                    if exp == 1 {
1783                        return Some(acc);
1784                    }
1785                }
1786                exp /= 2;
1787                base = try_opt!(base.checked_mul(base));
1788            }
1789        }
1790
1791        /// Strict exponentiation. Computes `self.pow(exp)`, panicking if
1792        /// overflow occurred.
1793        ///
1794        /// # Panics
1795        ///
1796        /// ## Overflow behavior
1797        ///
1798        /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
1799        ///
1800        /// # Examples
1801        ///
1802        /// Basic usage:
1803        ///
1804        /// ```
1805        /// #![feature(strict_overflow_ops)]
1806        #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".strict_pow(5), 32);")]
1807        /// ```
1808        ///
1809        /// The following panics because of overflow:
1810        ///
1811        /// ```should_panic
1812        /// #![feature(strict_overflow_ops)]
1813        #[doc = concat!("let _ = ", stringify!($SelfT), "::MAX.strict_pow(2);")]
1814        /// ```
1815        #[unstable(feature = "strict_overflow_ops", issue = "118260")]
1816        #[must_use = "this returns the result of the operation, \
1817                      without modifying the original"]
1818        #[inline]
1819        #[track_caller]
1820        pub const fn strict_pow(self, mut exp: u32) -> Self {
1821            if exp == 0 {
1822                return 1;
1823            }
1824            let mut base = self;
1825            let mut acc: Self = 1;
1826
1827            loop {
1828                if (exp & 1) == 1 {
1829                    acc = acc.strict_mul(base);
1830                    // since exp!=0, finally the exp must be 1.
1831                    if exp == 1 {
1832                        return acc;
1833                    }
1834                }
1835                exp /= 2;
1836                base = base.strict_mul(base);
1837            }
1838        }
1839
1840        /// Saturating integer addition. Computes `self + rhs`, saturating at
1841        /// the numeric bounds instead of overflowing.
1842        ///
1843        /// # Examples
1844        ///
1845        /// Basic usage:
1846        ///
1847        /// ```
1848        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);")]
1849        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(127), ", stringify!($SelfT), "::MAX);")]
1850        /// ```
1851        #[stable(feature = "rust1", since = "1.0.0")]
1852        #[must_use = "this returns the result of the operation, \
1853                      without modifying the original"]
1854        #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1855        #[inline(always)]
1856        pub const fn saturating_add(self, rhs: Self) -> Self {
1857            intrinsics::saturating_add(self, rhs)
1858        }
1859
1860        /// Saturating addition with a signed integer. Computes `self + rhs`,
1861        /// saturating at the numeric bounds instead of overflowing.
1862        ///
1863        /// # Examples
1864        ///
1865        /// Basic usage:
1866        ///
1867        /// ```
1868        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_signed(2), 3);")]
1869        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_signed(-2), 0);")]
1870        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).saturating_add_signed(4), ", stringify!($SelfT), "::MAX);")]
1871        /// ```
1872        #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
1873        #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
1874        #[must_use = "this returns the result of the operation, \
1875                      without modifying the original"]
1876        #[inline]
1877        pub const fn saturating_add_signed(self, rhs: $SignedT) -> Self {
1878            let (res, overflow) = self.overflowing_add(rhs as Self);
1879            if overflow == (rhs < 0) {
1880                res
1881            } else if overflow {
1882                Self::MAX
1883            } else {
1884                0
1885            }
1886        }
1887
1888        /// Saturating integer subtraction. Computes `self - rhs`, saturating
1889        /// at the numeric bounds instead of overflowing.
1890        ///
1891        /// # Examples
1892        ///
1893        /// Basic usage:
1894        ///
1895        /// ```
1896        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);")]
1897        #[doc = concat!("assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);")]
1898        /// ```
1899        #[stable(feature = "rust1", since = "1.0.0")]
1900        #[must_use = "this returns the result of the operation, \
1901                      without modifying the original"]
1902        #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1903        #[inline(always)]
1904        pub const fn saturating_sub(self, rhs: Self) -> Self {
1905            intrinsics::saturating_sub(self, rhs)
1906        }
1907
1908        /// Saturating integer subtraction. Computes `self` - `rhs`, saturating at
1909        /// the numeric bounds instead of overflowing.
1910        ///
1911        /// # Examples
1912        ///
1913        /// Basic usage:
1914        ///
1915        /// ```
1916        /// #![feature(mixed_integer_ops_unsigned_sub)]
1917        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_sub_signed(2), 0);")]
1918        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_sub_signed(-2), 3);")]
1919        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).saturating_sub_signed(-4), ", stringify!($SelfT), "::MAX);")]
1920        /// ```
1921        #[unstable(feature = "mixed_integer_ops_unsigned_sub", issue = "126043")]
1922        #[must_use = "this returns the result of the operation, \
1923                      without modifying the original"]
1924        #[inline]
1925        pub const fn saturating_sub_signed(self, rhs: $SignedT) -> Self {
1926            let (res, overflow) = self.overflowing_sub_signed(rhs);
1927
1928            if !overflow {
1929                res
1930            } else if rhs < 0 {
1931                Self::MAX
1932            } else {
1933                0
1934            }
1935        }
1936
1937        /// Saturating integer multiplication. Computes `self * rhs`,
1938        /// saturating at the numeric bounds instead of overflowing.
1939        ///
1940        /// # Examples
1941        ///
1942        /// Basic usage:
1943        ///
1944        /// ```
1945        #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);")]
1946        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),"::MAX);")]
1947        /// ```
1948        #[stable(feature = "wrapping", since = "1.7.0")]
1949        #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1950        #[must_use = "this returns the result of the operation, \
1951                      without modifying the original"]
1952        #[inline]
1953        pub const fn saturating_mul(self, rhs: Self) -> Self {
1954            match self.checked_mul(rhs) {
1955                Some(x) => x,
1956                None => Self::MAX,
1957            }
1958        }
1959
1960        /// Saturating integer division. Computes `self / rhs`, saturating at the
1961        /// numeric bounds instead of overflowing.
1962        ///
1963        /// # Panics
1964        ///
1965        /// This function will panic if `rhs` is zero.
1966        ///
1967        /// # Examples
1968        ///
1969        /// Basic usage:
1970        ///
1971        /// ```
1972        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".saturating_div(2), 2);")]
1973        ///
1974        /// ```
1975        #[stable(feature = "saturating_div", since = "1.58.0")]
1976        #[rustc_const_stable(feature = "saturating_div", since = "1.58.0")]
1977        #[must_use = "this returns the result of the operation, \
1978                      without modifying the original"]
1979        #[inline]
1980        #[track_caller]
1981        pub const fn saturating_div(self, rhs: Self) -> Self {
1982            // on unsigned types, there is no overflow in integer division
1983            self.wrapping_div(rhs)
1984        }
1985
1986        /// Saturating integer exponentiation. Computes `self.pow(exp)`,
1987        /// saturating at the numeric bounds instead of overflowing.
1988        ///
1989        /// # Examples
1990        ///
1991        /// Basic usage:
1992        ///
1993        /// ```
1994        #[doc = concat!("assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);")]
1995        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);")]
1996        /// ```
1997        #[stable(feature = "no_panic_pow", since = "1.34.0")]
1998        #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1999        #[must_use = "this returns the result of the operation, \
2000                      without modifying the original"]
2001        #[inline]
2002        pub const fn saturating_pow(self, exp: u32) -> Self {
2003            match self.checked_pow(exp) {
2004                Some(x) => x,
2005                None => Self::MAX,
2006            }
2007        }
2008
2009        /// Wrapping (modular) addition. Computes `self + rhs`,
2010        /// wrapping around at the boundary of the type.
2011        ///
2012        /// # Examples
2013        ///
2014        /// Basic usage:
2015        ///
2016        /// ```
2017        #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);")]
2018        #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);")]
2019        /// ```
2020        #[stable(feature = "rust1", since = "1.0.0")]
2021        #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2022        #[must_use = "this returns the result of the operation, \
2023                      without modifying the original"]
2024        #[inline(always)]
2025        pub const fn wrapping_add(self, rhs: Self) -> Self {
2026            intrinsics::wrapping_add(self, rhs)
2027        }
2028
2029        /// Wrapping (modular) addition with a signed integer. Computes
2030        /// `self + rhs`, wrapping around at the boundary of the type.
2031        ///
2032        /// # Examples
2033        ///
2034        /// Basic usage:
2035        ///
2036        /// ```
2037        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_add_signed(2), 3);")]
2038        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_add_signed(-2), ", stringify!($SelfT), "::MAX);")]
2039        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).wrapping_add_signed(4), 1);")]
2040        /// ```
2041        #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
2042        #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
2043        #[must_use = "this returns the result of the operation, \
2044                      without modifying the original"]
2045        #[inline]
2046        pub const fn wrapping_add_signed(self, rhs: $SignedT) -> Self {
2047            self.wrapping_add(rhs as Self)
2048        }
2049
2050        /// Wrapping (modular) subtraction. Computes `self - rhs`,
2051        /// wrapping around at the boundary of the type.
2052        ///
2053        /// # Examples
2054        ///
2055        /// Basic usage:
2056        ///
2057        /// ```
2058        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);")]
2059        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::MAX), 101);")]
2060        /// ```
2061        #[stable(feature = "rust1", since = "1.0.0")]
2062        #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2063        #[must_use = "this returns the result of the operation, \
2064                      without modifying the original"]
2065        #[inline(always)]
2066        pub const fn wrapping_sub(self, rhs: Self) -> Self {
2067            intrinsics::wrapping_sub(self, rhs)
2068        }
2069
2070        /// Wrapping (modular) subtraction with a signed integer. Computes
2071        /// `self - rhs`, wrapping around at the boundary of the type.
2072        ///
2073        /// # Examples
2074        ///
2075        /// Basic usage:
2076        ///
2077        /// ```
2078        /// #![feature(mixed_integer_ops_unsigned_sub)]
2079        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_sub_signed(2), ", stringify!($SelfT), "::MAX);")]
2080        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_sub_signed(-2), 3);")]
2081        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).wrapping_sub_signed(-4), 1);")]
2082        /// ```
2083        #[unstable(feature = "mixed_integer_ops_unsigned_sub", issue = "126043")]
2084        #[must_use = "this returns the result of the operation, \
2085                      without modifying the original"]
2086        #[inline]
2087        pub const fn wrapping_sub_signed(self, rhs: $SignedT) -> Self {
2088            self.wrapping_sub(rhs as Self)
2089        }
2090
2091        /// Wrapping (modular) multiplication. Computes `self *
2092        /// rhs`, wrapping around at the boundary of the type.
2093        ///
2094        /// # Examples
2095        ///
2096        /// Basic usage:
2097        ///
2098        /// Please note that this example is shared between integer types.
2099        /// Which explains why `u8` is used here.
2100        ///
2101        /// ```
2102        /// assert_eq!(10u8.wrapping_mul(12), 120);
2103        /// assert_eq!(25u8.wrapping_mul(12), 44);
2104        /// ```
2105        #[stable(feature = "rust1", since = "1.0.0")]
2106        #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2107        #[must_use = "this returns the result of the operation, \
2108                      without modifying the original"]
2109        #[inline(always)]
2110        pub const fn wrapping_mul(self, rhs: Self) -> Self {
2111            intrinsics::wrapping_mul(self, rhs)
2112        }
2113
2114        /// Wrapping (modular) division. Computes `self / rhs`.
2115        ///
2116        /// Wrapped division on unsigned types is just normal division. There's
2117        /// no way wrapping could ever happen. This function exists so that all
2118        /// operations are accounted for in the wrapping operations.
2119        ///
2120        /// # Panics
2121        ///
2122        /// This function will panic if `rhs` is zero.
2123        ///
2124        /// # Examples
2125        ///
2126        /// Basic usage:
2127        ///
2128        /// ```
2129        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);")]
2130        /// ```
2131        #[stable(feature = "num_wrapping", since = "1.2.0")]
2132        #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
2133        #[must_use = "this returns the result of the operation, \
2134                      without modifying the original"]
2135        #[inline(always)]
2136        #[track_caller]
2137        pub const fn wrapping_div(self, rhs: Self) -> Self {
2138            self / rhs
2139        }
2140
2141        /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
2142        ///
2143        /// Wrapped division on unsigned types is just normal division. There's
2144        /// no way wrapping could ever happen. This function exists so that all
2145        /// operations are accounted for in the wrapping operations. Since, for
2146        /// the positive integers, all common definitions of division are equal,
2147        /// this is exactly equal to `self.wrapping_div(rhs)`.
2148        ///
2149        /// # Panics
2150        ///
2151        /// This function will panic if `rhs` is zero.
2152        ///
2153        /// # Examples
2154        ///
2155        /// Basic usage:
2156        ///
2157        /// ```
2158        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);")]
2159        /// ```
2160        #[stable(feature = "euclidean_division", since = "1.38.0")]
2161        #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
2162        #[must_use = "this returns the result of the operation, \
2163                      without modifying the original"]
2164        #[inline(always)]
2165        #[track_caller]
2166        pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
2167            self / rhs
2168        }
2169
2170        /// Wrapping (modular) remainder. Computes `self % rhs`.
2171        ///
2172        /// Wrapped remainder calculation on unsigned types is just the regular
2173        /// remainder calculation. There's no way wrapping could ever happen.
2174        /// This function exists so that all operations are accounted for in the
2175        /// wrapping operations.
2176        ///
2177        /// # Panics
2178        ///
2179        /// This function will panic if `rhs` is zero.
2180        ///
2181        /// # Examples
2182        ///
2183        /// Basic usage:
2184        ///
2185        /// ```
2186        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);")]
2187        /// ```
2188        #[stable(feature = "num_wrapping", since = "1.2.0")]
2189        #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
2190        #[must_use = "this returns the result of the operation, \
2191                      without modifying the original"]
2192        #[inline(always)]
2193        #[track_caller]
2194        pub const fn wrapping_rem(self, rhs: Self) -> Self {
2195            self % rhs
2196        }
2197
2198        /// Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
2199        ///
2200        /// Wrapped modulo calculation on unsigned types is just the regular
2201        /// remainder calculation. There's no way wrapping could ever happen.
2202        /// This function exists so that all operations are accounted for in the
2203        /// wrapping operations. Since, for the positive integers, all common
2204        /// definitions of division are equal, this is exactly equal to
2205        /// `self.wrapping_rem(rhs)`.
2206        ///
2207        /// # Panics
2208        ///
2209        /// This function will panic if `rhs` is zero.
2210        ///
2211        /// # Examples
2212        ///
2213        /// Basic usage:
2214        ///
2215        /// ```
2216        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);")]
2217        /// ```
2218        #[stable(feature = "euclidean_division", since = "1.38.0")]
2219        #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
2220        #[must_use = "this returns the result of the operation, \
2221                      without modifying the original"]
2222        #[inline(always)]
2223        #[track_caller]
2224        pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
2225            self % rhs
2226        }
2227
2228        /// Wrapping (modular) negation. Computes `-self`,
2229        /// wrapping around at the boundary of the type.
2230        ///
2231        /// Since unsigned types do not have negative equivalents
2232        /// all applications of this function will wrap (except for `-0`).
2233        /// For values smaller than the corresponding signed type's maximum
2234        /// the result is the same as casting the corresponding signed value.
2235        /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
2236        /// `MAX` is the corresponding signed type's maximum.
2237        ///
2238        /// # Examples
2239        ///
2240        /// Basic usage:
2241        ///
2242        /// ```
2243        #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".wrapping_neg(), 0);")]
2244        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_neg(), 1);")]
2245        #[doc = concat!("assert_eq!(13_", stringify!($SelfT), ".wrapping_neg(), (!13) + 1);")]
2246        #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".wrapping_neg(), !(42 - 1));")]
2247        /// ```
2248        #[stable(feature = "num_wrapping", since = "1.2.0")]
2249        #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2250        #[must_use = "this returns the result of the operation, \
2251                      without modifying the original"]
2252        #[inline(always)]
2253        pub const fn wrapping_neg(self) -> Self {
2254            (0 as $SelfT).wrapping_sub(self)
2255        }
2256
2257        /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
2258        /// where `mask` removes any high-order bits of `rhs` that
2259        /// would cause the shift to exceed the bitwidth of the type.
2260        ///
2261        /// Note that this is *not* the same as a rotate-left; the
2262        /// RHS of a wrapping shift-left is restricted to the range
2263        /// of the type, rather than the bits shifted out of the LHS
2264        /// being returned to the other end. The primitive integer
2265        /// types all implement a [`rotate_left`](Self::rotate_left) function,
2266        /// which may be what you want instead.
2267        ///
2268        /// # Examples
2269        ///
2270        /// Basic usage:
2271        ///
2272        /// ```
2273        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);")]
2274        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);")]
2275        /// ```
2276        #[stable(feature = "num_wrapping", since = "1.2.0")]
2277        #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2278        #[must_use = "this returns the result of the operation, \
2279                      without modifying the original"]
2280        #[inline(always)]
2281        pub const fn wrapping_shl(self, rhs: u32) -> Self {
2282            // SAFETY: the masking by the bitsize of the type ensures that we do not shift
2283            // out of bounds
2284            unsafe {
2285                self.unchecked_shl(rhs & (Self::BITS - 1))
2286            }
2287        }
2288
2289        /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
2290        /// where `mask` removes any high-order bits of `rhs` that
2291        /// would cause the shift to exceed the bitwidth of the type.
2292        ///
2293        /// Note that this is *not* the same as a rotate-right; the
2294        /// RHS of a wrapping shift-right is restricted to the range
2295        /// of the type, rather than the bits shifted out of the LHS
2296        /// being returned to the other end. The primitive integer
2297        /// types all implement a [`rotate_right`](Self::rotate_right) function,
2298        /// which may be what you want instead.
2299        ///
2300        /// # Examples
2301        ///
2302        /// Basic usage:
2303        ///
2304        /// ```
2305        #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);")]
2306        #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);")]
2307        /// ```
2308        #[stable(feature = "num_wrapping", since = "1.2.0")]
2309        #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2310        #[must_use = "this returns the result of the operation, \
2311                      without modifying the original"]
2312        #[inline(always)]
2313        pub const fn wrapping_shr(self, rhs: u32) -> Self {
2314            // SAFETY: the masking by the bitsize of the type ensures that we do not shift
2315            // out of bounds
2316            unsafe {
2317                self.unchecked_shr(rhs & (Self::BITS - 1))
2318            }
2319        }
2320
2321        /// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
2322        /// wrapping around at the boundary of the type.
2323        ///
2324        /// # Examples
2325        ///
2326        /// Basic usage:
2327        ///
2328        /// ```
2329        #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);")]
2330        /// assert_eq!(3u8.wrapping_pow(6), 217);
2331        /// ```
2332        #[stable(feature = "no_panic_pow", since = "1.34.0")]
2333        #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2334        #[must_use = "this returns the result of the operation, \
2335                      without modifying the original"]
2336        #[inline]
2337        pub const fn wrapping_pow(self, mut exp: u32) -> Self {
2338            if exp == 0 {
2339                return 1;
2340            }
2341            let mut base = self;
2342            let mut acc: Self = 1;
2343
2344            if intrinsics::is_val_statically_known(exp) {
2345                while exp > 1 {
2346                    if (exp & 1) == 1 {
2347                        acc = acc.wrapping_mul(base);
2348                    }
2349                    exp /= 2;
2350                    base = base.wrapping_mul(base);
2351                }
2352
2353                // since exp!=0, finally the exp must be 1.
2354                // Deal with the final bit of the exponent separately, since
2355                // squaring the base afterwards is not necessary.
2356                acc.wrapping_mul(base)
2357            } else {
2358                // This is faster than the above when the exponent is not known
2359                // at compile time. We can't use the same code for the constant
2360                // exponent case because LLVM is currently unable to unroll
2361                // this loop.
2362                loop {
2363                    if (exp & 1) == 1 {
2364                        acc = acc.wrapping_mul(base);
2365                        // since exp!=0, finally the exp must be 1.
2366                        if exp == 1 {
2367                            return acc;
2368                        }
2369                    }
2370                    exp /= 2;
2371                    base = base.wrapping_mul(base);
2372                }
2373            }
2374        }
2375
2376        /// Calculates `self` + `rhs`.
2377        ///
2378        /// Returns a tuple of the addition along with a boolean indicating
2379        /// whether an arithmetic overflow would occur. If an overflow would
2380        /// have occurred then the wrapped value is returned.
2381        ///
2382        /// # Examples
2383        ///
2384        /// Basic usage:
2385        ///
2386        /// ```
2387        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));")]
2388        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));")]
2389        /// ```
2390        #[stable(feature = "wrapping", since = "1.7.0")]
2391        #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2392        #[must_use = "this returns the result of the operation, \
2393                      without modifying the original"]
2394        #[inline(always)]
2395        pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
2396            let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
2397            (a as Self, b)
2398        }
2399
2400        /// Calculates `self` + `rhs` + `carry` and returns a tuple containing
2401        /// the sum and the output carry.
2402        ///
2403        /// Performs "ternary addition" of two integer operands and a carry-in
2404        /// bit, and returns an output integer and a carry-out bit. This allows
2405        /// chaining together multiple additions to create a wider addition, and
2406        /// can be useful for bignum addition.
2407        ///
2408        #[doc = concat!("This can be thought of as a ", stringify!($BITS), "-bit \"full adder\", in the electronics sense.")]
2409        ///
2410        /// If the input carry is false, this method is equivalent to
2411        /// [`overflowing_add`](Self::overflowing_add), and the output carry is
2412        /// equal to the overflow flag. Note that although carry and overflow
2413        /// flags are similar for unsigned integers, they are different for
2414        /// signed integers.
2415        ///
2416        /// # Examples
2417        ///
2418        /// ```
2419        /// #![feature(bigint_helper_methods)]
2420        ///
2421        #[doc = concat!("//    3  MAX    (a = 3 × 2^", stringify!($BITS), " + 2^", stringify!($BITS), " - 1)")]
2422        #[doc = concat!("// +  5    7    (b = 5 × 2^", stringify!($BITS), " + 7)")]
2423        /// // ---------
2424        #[doc = concat!("//    9    6    (sum = 9 × 2^", stringify!($BITS), " + 6)")]
2425        ///
2426        #[doc = concat!("let (a1, a0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (3, ", stringify!($SelfT), "::MAX);")]
2427        #[doc = concat!("let (b1, b0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (5, 7);")]
2428        /// let carry0 = false;
2429        ///
2430        /// let (sum0, carry1) = a0.carrying_add(b0, carry0);
2431        /// assert_eq!(carry1, true);
2432        /// let (sum1, carry2) = a1.carrying_add(b1, carry1);
2433        /// assert_eq!(carry2, false);
2434        ///
2435        /// assert_eq!((sum1, sum0), (9, 6));
2436        /// ```
2437        #[unstable(feature = "bigint_helper_methods", issue = "85532")]
2438        #[rustc_const_unstable(feature = "bigint_helper_methods", issue = "85532")]
2439        #[must_use = "this returns the result of the operation, \
2440                      without modifying the original"]
2441        #[inline]
2442        pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
2443            // note: longer-term this should be done via an intrinsic, but this has been shown
2444            //   to generate optimal code for now, and LLVM doesn't have an equivalent intrinsic
2445            let (a, c1) = self.overflowing_add(rhs);
2446            let (b, c2) = a.overflowing_add(carry as $SelfT);
2447            // Ideally LLVM would know this is disjoint without us telling them,
2448            // but it doesn't <https://github.com/llvm/llvm-project/issues/118162>
2449            // SAFETY: Only one of `c1` and `c2` can be set.
2450            // For c1 to be set we need to have overflowed, but if we did then
2451            // `a` is at most `MAX-1`, which means that `c2` cannot possibly
2452            // overflow because it's adding at most `1` (since it came from `bool`)
2453            (b, unsafe { intrinsics::disjoint_bitor(c1, c2) })
2454        }
2455
2456        /// Calculates `self` + `rhs` with a signed `rhs`.
2457        ///
2458        /// Returns a tuple of the addition along with a boolean indicating
2459        /// whether an arithmetic overflow would occur. If an overflow would
2460        /// have occurred then the wrapped value is returned.
2461        ///
2462        /// # Examples
2463        ///
2464        /// Basic usage:
2465        ///
2466        /// ```
2467        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_signed(2), (3, false));")]
2468        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_signed(-2), (", stringify!($SelfT), "::MAX, true));")]
2469        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).overflowing_add_signed(4), (1, true));")]
2470        /// ```
2471        #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
2472        #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
2473        #[must_use = "this returns the result of the operation, \
2474                      without modifying the original"]
2475        #[inline]
2476        pub const fn overflowing_add_signed(self, rhs: $SignedT) -> (Self, bool) {
2477            let (res, overflowed) = self.overflowing_add(rhs as Self);
2478            (res, overflowed ^ (rhs < 0))
2479        }
2480
2481        /// Calculates `self` - `rhs`.
2482        ///
2483        /// Returns a tuple of the subtraction along with a boolean indicating
2484        /// whether an arithmetic overflow would occur. If an overflow would
2485        /// have occurred then the wrapped value is returned.
2486        ///
2487        /// # Examples
2488        ///
2489        /// Basic usage:
2490        ///
2491        /// ```
2492        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));")]
2493        #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")]
2494        /// ```
2495        #[stable(feature = "wrapping", since = "1.7.0")]
2496        #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2497        #[must_use = "this returns the result of the operation, \
2498                      without modifying the original"]
2499        #[inline(always)]
2500        pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
2501            let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
2502            (a as Self, b)
2503        }
2504
2505        /// Calculates `self` &minus; `rhs` &minus; `borrow` and returns a tuple
2506        /// containing the difference and the output borrow.
2507        ///
2508        /// Performs "ternary subtraction" by subtracting both an integer
2509        /// operand and a borrow-in bit from `self`, and returns an output
2510        /// integer and a borrow-out bit. This allows chaining together multiple
2511        /// subtractions to create a wider subtraction, and can be useful for
2512        /// bignum subtraction.
2513        ///
2514        /// # Examples
2515        ///
2516        /// ```
2517        /// #![feature(bigint_helper_methods)]
2518        ///
2519        #[doc = concat!("//    9    6    (a = 9 × 2^", stringify!($BITS), " + 6)")]
2520        #[doc = concat!("// -  5    7    (b = 5 × 2^", stringify!($BITS), " + 7)")]
2521        /// // ---------
2522        #[doc = concat!("//    3  MAX    (diff = 3 × 2^", stringify!($BITS), " + 2^", stringify!($BITS), " - 1)")]
2523        ///
2524        #[doc = concat!("let (a1, a0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (9, 6);")]
2525        #[doc = concat!("let (b1, b0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (5, 7);")]
2526        /// let borrow0 = false;
2527        ///
2528        /// let (diff0, borrow1) = a0.borrowing_sub(b0, borrow0);
2529        /// assert_eq!(borrow1, true);
2530        /// let (diff1, borrow2) = a1.borrowing_sub(b1, borrow1);
2531        /// assert_eq!(borrow2, false);
2532        ///
2533        #[doc = concat!("assert_eq!((diff1, diff0), (3, ", stringify!($SelfT), "::MAX));")]
2534        /// ```
2535        #[unstable(feature = "bigint_helper_methods", issue = "85532")]
2536        #[rustc_const_unstable(feature = "bigint_helper_methods", issue = "85532")]
2537        #[must_use = "this returns the result of the operation, \
2538                      without modifying the original"]
2539        #[inline]
2540        pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
2541            // note: longer-term this should be done via an intrinsic, but this has been shown
2542            //   to generate optimal code for now, and LLVM doesn't have an equivalent intrinsic
2543            let (a, c1) = self.overflowing_sub(rhs);
2544            let (b, c2) = a.overflowing_sub(borrow as $SelfT);
2545            // SAFETY: Only one of `c1` and `c2` can be set.
2546            // For c1 to be set we need to have underflowed, but if we did then
2547            // `a` is nonzero, which means that `c2` cannot possibly
2548            // underflow because it's subtracting at most `1` (since it came from `bool`)
2549            (b, unsafe { intrinsics::disjoint_bitor(c1, c2) })
2550        }
2551
2552        /// Calculates `self` - `rhs` with a signed `rhs`
2553        ///
2554        /// Returns a tuple of the subtraction along with a boolean indicating
2555        /// whether an arithmetic overflow would occur. If an overflow would
2556        /// have occurred then the wrapped value is returned.
2557        ///
2558        /// # Examples
2559        ///
2560        /// Basic usage:
2561        ///
2562        /// ```
2563        /// #![feature(mixed_integer_ops_unsigned_sub)]
2564        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_sub_signed(2), (", stringify!($SelfT), "::MAX, true));")]
2565        #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_sub_signed(-2), (3, false));")]
2566        #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).overflowing_sub_signed(-4), (1, true));")]
2567        /// ```
2568        #[unstable(feature = "mixed_integer_ops_unsigned_sub", issue = "126043")]
2569        #[must_use = "this returns the result of the operation, \
2570                      without modifying the original"]
2571        #[inline]
2572        pub const fn overflowing_sub_signed(self, rhs: $SignedT) -> (Self, bool) {
2573            let (res, overflow) = self.overflowing_sub(rhs as Self);
2574
2575            (res, overflow ^ (rhs < 0))
2576        }
2577
2578        /// Computes the absolute difference between `self` and `other`.
2579        ///
2580        /// # Examples
2581        ///
2582        /// Basic usage:
2583        ///
2584        /// ```
2585        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(80), 20", stringify!($SelfT), ");")]
2586        #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(110), 10", stringify!($SelfT), ");")]
2587        /// ```
2588        #[stable(feature = "int_abs_diff", since = "1.60.0")]
2589        #[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
2590        #[must_use = "this returns the result of the operation, \
2591                      without modifying the original"]
2592        #[inline]
2593        pub const fn abs_diff(self, other: Self) -> Self {
2594            if size_of::<Self>() == 1 {
2595                // Trick LLVM into generating the psadbw instruction when SSE2
2596                // is available and this function is autovectorized for u8's.
2597                (self as i32).wrapping_sub(other as i32).abs() as Self
2598            } else {
2599                if self < other {
2600                    other - self
2601                } else {
2602                    self - other
2603                }
2604            }
2605        }
2606
2607        /// Calculates the multiplication of `self` and `rhs`.
2608        ///
2609        /// Returns a tuple of the multiplication along with a boolean
2610        /// indicating whether an arithmetic overflow would occur. If an
2611        /// overflow would have occurred then the wrapped value is returned.
2612        ///
2613        /// # Examples
2614        ///
2615        /// Basic usage:
2616        ///
2617        /// Please note that this example is shared between integer types.
2618        /// Which explains why `u32` is used here.
2619        ///
2620        /// ```
2621        /// assert_eq!(5u32.overflowing_mul(2), (10, false));
2622        /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
2623        /// ```
2624        #[stable(feature = "wrapping", since = "1.7.0")]
2625        #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2626        #[must_use = "this returns the result of the operation, \
2627                          without modifying the original"]
2628        #[inline(always)]
2629        pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
2630            let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
2631            (a as Self, b)
2632        }
2633
2634        /// Calculates the complete product `self * rhs` without the possibility to overflow.
2635        ///
2636        /// This returns the low-order (wrapping) bits and the high-order (overflow) bits
2637        /// of the result as two separate values, in that order.
2638        ///
2639        /// If you also need to add a carry to the wide result, then you want
2640        /// [`Self::carrying_mul`] instead.
2641        ///
2642        /// # Examples
2643        ///
2644        /// Basic usage:
2645        ///
2646        /// Please note that this example is shared between integer types.
2647        /// Which explains why `u32` is used here.
2648        ///
2649        /// ```
2650        /// #![feature(bigint_helper_methods)]
2651        /// assert_eq!(5u32.widening_mul(2), (10, 0));
2652        /// assert_eq!(1_000_000_000u32.widening_mul(10), (1410065408, 2));
2653        /// ```
2654        #[unstable(feature = "bigint_helper_methods", issue = "85532")]
2655        #[rustc_const_unstable(feature = "bigint_helper_methods", issue = "85532")]
2656        #[must_use = "this returns the result of the operation, \
2657                      without modifying the original"]
2658        #[inline]
2659        pub const fn widening_mul(self, rhs: Self) -> (Self, Self) {
2660            Self::carrying_mul_add(self, rhs, 0, 0)
2661        }
2662
2663        /// Calculates the "full multiplication" `self * rhs + carry`
2664        /// without the possibility to overflow.
2665        ///
2666        /// This returns the low-order (wrapping) bits and the high-order (overflow) bits
2667        /// of the result as two separate values, in that order.
2668        ///
2669        /// Performs "long multiplication" which takes in an extra amount to add, and may return an
2670        /// additional amount of overflow. This allows for chaining together multiple
2671        /// multiplications to create "big integers" which represent larger values.
2672        ///
2673        /// If you don't need the `carry`, then you can use [`Self::widening_mul`] instead.
2674        ///
2675        /// # Examples
2676        ///
2677        /// Basic usage:
2678        ///
2679        /// Please note that this example is shared between integer types.
2680        /// Which explains why `u32` is used here.
2681        ///
2682        /// ```
2683        /// #![feature(bigint_helper_methods)]
2684        /// assert_eq!(5u32.carrying_mul(2, 0), (10, 0));
2685        /// assert_eq!(5u32.carrying_mul(2, 10), (20, 0));
2686        /// assert_eq!(1_000_000_000u32.carrying_mul(10, 0), (1410065408, 2));
2687        /// assert_eq!(1_000_000_000u32.carrying_mul(10, 10), (1410065418, 2));
2688        #[doc = concat!("assert_eq!(",
2689            stringify!($SelfT), "::MAX.carrying_mul(", stringify!($SelfT), "::MAX, ", stringify!($SelfT), "::MAX), ",
2690            "(0, ", stringify!($SelfT), "::MAX));"
2691        )]
2692        /// ```
2693        ///
2694        /// This is the core operation needed for scalar multiplication when
2695        /// implementing it for wider-than-native types.
2696        ///
2697        /// ```
2698        /// #![feature(bigint_helper_methods)]
2699        /// fn scalar_mul_eq(little_endian_digits: &mut Vec<u16>, multiplicand: u16) {
2700        ///     let mut carry = 0;
2701        ///     for d in little_endian_digits.iter_mut() {
2702        ///         (*d, carry) = d.carrying_mul(multiplicand, carry);
2703        ///     }
2704        ///     if carry != 0 {
2705        ///         little_endian_digits.push(carry);
2706        ///     }
2707        /// }
2708        ///
2709        /// let mut v = vec![10, 20];
2710        /// scalar_mul_eq(&mut v, 3);
2711        /// assert_eq!(v, [30, 60]);
2712        ///
2713        /// assert_eq!(0x87654321_u64 * 0xFEED, 0x86D3D159E38D);
2714        /// let mut v = vec![0x4321, 0x8765];
2715        /// scalar_mul_eq(&mut v, 0xFEED);
2716        /// assert_eq!(v, [0xE38D, 0xD159, 0x86D3]);
2717        /// ```
2718        ///
2719        /// If `carry` is zero, this is similar to [`overflowing_mul`](Self::overflowing_mul),
2720        /// except that it gives the value of the overflow instead of just whether one happened:
2721        ///
2722        /// ```
2723        /// #![feature(bigint_helper_methods)]
2724        /// let r = u8::carrying_mul(7, 13, 0);
2725        /// assert_eq!((r.0, r.1 != 0), u8::overflowing_mul(7, 13));
2726        /// let r = u8::carrying_mul(13, 42, 0);
2727        /// assert_eq!((r.0, r.1 != 0), u8::overflowing_mul(13, 42));
2728        /// ```
2729        ///
2730        /// The value of the first field in the returned tuple matches what you'd get
2731        /// by combining the [`wrapping_mul`](Self::wrapping_mul) and
2732        /// [`wrapping_add`](Self::wrapping_add) methods:
2733        ///
2734        /// ```
2735        /// #![feature(bigint_helper_methods)]
2736        /// assert_eq!(
2737        ///     789_u16.carrying_mul(456, 123).0,
2738        ///     789_u16.wrapping_mul(456).wrapping_add(123),
2739        /// );
2740        /// ```
2741        #[unstable(feature = "bigint_helper_methods", issue = "85532")]
2742        #[rustc_const_unstable(feature = "bigint_helper_methods", issue = "85532")]
2743        #[must_use = "this returns the result of the operation, \
2744                      without modifying the original"]
2745        #[inline]
2746        pub const fn carrying_mul(self, rhs: Self, carry: Self) -> (Self, Self) {
2747            Self::carrying_mul_add(self, rhs, carry, 0)
2748        }
2749
2750        /// Calculates the "full multiplication" `self * rhs + carry1 + carry2`
2751        /// without the possibility to overflow.
2752        ///
2753        /// This returns the low-order (wrapping) bits and the high-order (overflow) bits
2754        /// of the result as two separate values, in that order.
2755        ///
2756        /// Performs "long multiplication" which takes in an extra amount to add, and may return an
2757        /// additional amount of overflow. This allows for chaining together multiple
2758        /// multiplications to create "big integers" which represent larger values.
2759        ///
2760        /// If you don't need either `carry`, then you can use [`Self::widening_mul`] instead,
2761        /// and if you only need one `carry`, then you can use [`Self::carrying_mul`] instead.
2762        ///
2763        /// # Examples
2764        ///
2765        /// Basic usage:
2766        ///
2767        /// Please note that this example is shared between integer types,
2768        /// which explains why `u32` is used here.
2769        ///
2770        /// ```
2771        /// #![feature(bigint_helper_methods)]
2772        /// assert_eq!(5u32.carrying_mul_add(2, 0, 0), (10, 0));
2773        /// assert_eq!(5u32.carrying_mul_add(2, 10, 10), (30, 0));
2774        /// assert_eq!(1_000_000_000u32.carrying_mul_add(10, 0, 0), (1410065408, 2));
2775        /// assert_eq!(1_000_000_000u32.carrying_mul_add(10, 10, 10), (1410065428, 2));
2776        #[doc = concat!("assert_eq!(",
2777            stringify!($SelfT), "::MAX.carrying_mul_add(", stringify!($SelfT), "::MAX, ", stringify!($SelfT), "::MAX, ", stringify!($SelfT), "::MAX), ",
2778            "(", stringify!($SelfT), "::MAX, ", stringify!($SelfT), "::MAX));"
2779        )]
2780        /// ```
2781        ///
2782        /// This is the core per-digit operation for "grade school" O(n²) multiplication.
2783        ///
2784        /// Please note that this example is shared between integer types,
2785        /// using `u8` for simplicity of the demonstration.
2786        ///
2787        /// ```
2788        /// #![feature(bigint_helper_methods)]
2789        ///
2790        /// fn quadratic_mul<const N: usize>(a: [u8; N], b: [u8; N]) -> [u8; N] {
2791        ///     let mut out = [0; N];
2792        ///     for j in 0..N {
2793        ///         let mut carry = 0;
2794        ///         for i in 0..(N - j) {
2795        ///             (out[j + i], carry) = u8::carrying_mul_add(a[i], b[j], out[j + i], carry);
2796        ///         }
2797        ///     }
2798        ///     out
2799        /// }
2800        ///
2801        /// // -1 * -1 == 1
2802        /// assert_eq!(quadratic_mul([0xFF; 3], [0xFF; 3]), [1, 0, 0]);
2803        ///
2804        /// assert_eq!(u32::wrapping_mul(0x9e3779b9, 0x7f4a7c15), 0xCFFC982D);
2805        /// assert_eq!(
2806        ///     quadratic_mul(u32::to_le_bytes(0x9e3779b9), u32::to_le_bytes(0x7f4a7c15)),
2807        ///     u32::to_le_bytes(0xCFFC982D)
2808        /// );
2809        /// ```
2810        #[unstable(feature = "bigint_helper_methods", issue = "85532")]
2811        #[rustc_const_unstable(feature = "bigint_helper_methods", issue = "85532")]
2812        #[must_use = "this returns the result of the operation, \
2813                      without modifying the original"]
2814        #[inline]
2815        pub const fn carrying_mul_add(self, rhs: Self, carry: Self, add: Self) -> (Self, Self) {
2816            intrinsics::carrying_mul_add(self, rhs, carry, add)
2817        }
2818
2819        /// Calculates the divisor when `self` is divided by `rhs`.
2820        ///
2821        /// Returns a tuple of the divisor along with a boolean indicating
2822        /// whether an arithmetic overflow would occur. Note that for unsigned
2823        /// integers overflow never occurs, so the second value is always
2824        /// `false`.
2825        ///
2826        /// # Panics
2827        ///
2828        /// This function will panic if `rhs` is zero.
2829        ///
2830        /// # Examples
2831        ///
2832        /// Basic usage:
2833        ///
2834        /// ```
2835        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));")]
2836        /// ```
2837        #[inline(always)]
2838        #[stable(feature = "wrapping", since = "1.7.0")]
2839        #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
2840        #[must_use = "this returns the result of the operation, \
2841                      without modifying the original"]
2842        #[track_caller]
2843        pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
2844            (self / rhs, false)
2845        }
2846
2847        /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
2848        ///
2849        /// Returns a tuple of the divisor along with a boolean indicating
2850        /// whether an arithmetic overflow would occur. Note that for unsigned
2851        /// integers overflow never occurs, so the second value is always
2852        /// `false`.
2853        /// Since, for the positive integers, all common
2854        /// definitions of division are equal, this
2855        /// is exactly equal to `self.overflowing_div(rhs)`.
2856        ///
2857        /// # Panics
2858        ///
2859        /// This function will panic if `rhs` is zero.
2860        ///
2861        /// # Examples
2862        ///
2863        /// Basic usage:
2864        ///
2865        /// ```
2866        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));")]
2867        /// ```
2868        #[inline(always)]
2869        #[stable(feature = "euclidean_division", since = "1.38.0")]
2870        #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
2871        #[must_use = "this returns the result of the operation, \
2872                      without modifying the original"]
2873        #[track_caller]
2874        pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
2875            (self / rhs, false)
2876        }
2877
2878        /// Calculates the remainder when `self` is divided by `rhs`.
2879        ///
2880        /// Returns a tuple of the remainder after dividing along with a boolean
2881        /// indicating whether an arithmetic overflow would occur. Note that for
2882        /// unsigned integers overflow never occurs, so the second value is
2883        /// always `false`.
2884        ///
2885        /// # Panics
2886        ///
2887        /// This function will panic if `rhs` is zero.
2888        ///
2889        /// # Examples
2890        ///
2891        /// Basic usage:
2892        ///
2893        /// ```
2894        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));")]
2895        /// ```
2896        #[inline(always)]
2897        #[stable(feature = "wrapping", since = "1.7.0")]
2898        #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
2899        #[must_use = "this returns the result of the operation, \
2900                      without modifying the original"]
2901        #[track_caller]
2902        pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
2903            (self % rhs, false)
2904        }
2905
2906        /// Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
2907        ///
2908        /// Returns a tuple of the modulo after dividing along with a boolean
2909        /// indicating whether an arithmetic overflow would occur. Note that for
2910        /// unsigned integers overflow never occurs, so the second value is
2911        /// always `false`.
2912        /// Since, for the positive integers, all common
2913        /// definitions of division are equal, this operation
2914        /// is exactly equal to `self.overflowing_rem(rhs)`.
2915        ///
2916        /// # Panics
2917        ///
2918        /// This function will panic if `rhs` is zero.
2919        ///
2920        /// # Examples
2921        ///
2922        /// Basic usage:
2923        ///
2924        /// ```
2925        #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));")]
2926        /// ```
2927        #[inline(always)]
2928        #[stable(feature = "euclidean_division", since = "1.38.0")]
2929        #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
2930        #[must_use = "this returns the result of the operation, \
2931                      without modifying the original"]
2932        #[track_caller]
2933        pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
2934            (self % rhs, false)
2935        }
2936
2937        /// Negates self in an overflowing fashion.
2938        ///
2939        /// Returns `!self + 1` using wrapping operations to return the value
2940        /// that represents the negation of this unsigned value. Note that for
2941        /// positive unsigned values overflow always occurs, but negating 0 does
2942        /// not overflow.
2943        ///
2944        /// # Examples
2945        ///
2946        /// Basic usage:
2947        ///
2948        /// ```
2949        #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));")]
2950        #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT), ", true));")]
2951        /// ```
2952        #[inline(always)]
2953        #[stable(feature = "wrapping", since = "1.7.0")]
2954        #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2955        #[must_use = "this returns the result of the operation, \
2956                      without modifying the original"]
2957        pub const fn overflowing_neg(self) -> (Self, bool) {
2958            ((!self).wrapping_add(1), self != 0)
2959        }
2960
2961        /// Shifts self left by `rhs` bits.
2962        ///
2963        /// Returns a tuple of the shifted version of self along with a boolean
2964        /// indicating whether the shift value was larger than or equal to the
2965        /// number of bits. If the shift value is too large, then value is
2966        /// masked (N-1) where N is the number of bits, and this value is then
2967        /// used to perform the shift.
2968        ///
2969        /// # Examples
2970        ///
2971        /// Basic usage:
2972        ///
2973        /// ```
2974        #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));")]
2975        #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));")]
2976        #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shl(", stringify!($BITS_MINUS_ONE), "), (0, false));")]
2977        /// ```
2978        #[stable(feature = "wrapping", since = "1.7.0")]
2979        #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2980        #[must_use = "this returns the result of the operation, \
2981                      without modifying the original"]
2982        #[inline(always)]
2983        pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
2984            (self.wrapping_shl(rhs), rhs >= Self::BITS)
2985        }
2986
2987        /// Shifts self right by `rhs` bits.
2988        ///
2989        /// Returns a tuple of the shifted version of self along with a boolean
2990        /// indicating whether the shift value was larger than or equal to the
2991        /// number of bits. If the shift value is too large, then value is
2992        /// masked (N-1) where N is the number of bits, and this value is then
2993        /// used to perform the shift.
2994        ///
2995        /// # Examples
2996        ///
2997        /// Basic usage:
2998        ///
2999        /// ```
3000        #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));")]
3001        #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));")]
3002        /// ```
3003        #[stable(feature = "wrapping", since = "1.7.0")]
3004        #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3005        #[must_use = "this returns the result of the operation, \
3006                      without modifying the original"]
3007        #[inline(always)]
3008        pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3009            (self.wrapping_shr(rhs), rhs >= Self::BITS)
3010        }
3011
3012        /// Raises self to the power of `exp`, using exponentiation by squaring.
3013        ///
3014        /// Returns a tuple of the exponentiation along with a bool indicating
3015        /// whether an overflow happened.
3016        ///
3017        /// # Examples
3018        ///
3019        /// Basic usage:
3020        ///
3021        /// ```
3022        #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));")]
3023        /// assert_eq!(3u8.overflowing_pow(6), (217, true));
3024        /// ```
3025        #[stable(feature = "no_panic_pow", since = "1.34.0")]
3026        #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
3027        #[must_use = "this returns the result of the operation, \
3028                      without modifying the original"]
3029        #[inline]
3030        pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3031            if exp == 0{
3032                return (1,false);
3033            }
3034            let mut base = self;
3035            let mut acc: Self = 1;
3036            let mut overflown = false;
3037            // Scratch space for storing results of overflowing_mul.
3038            let mut r;
3039
3040            loop {
3041                if (exp & 1) == 1 {
3042                    r = acc.overflowing_mul(base);
3043                    // since exp!=0, finally the exp must be 1.
3044                    if exp == 1 {
3045                        r.1 |= overflown;
3046                        return r;
3047                    }
3048                    acc = r.0;
3049                    overflown |= r.1;
3050                }
3051                exp /= 2;
3052                r = base.overflowing_mul(base);
3053                base = r.0;
3054                overflown |= r.1;
3055            }
3056        }
3057
3058        /// Raises self to the power of `exp`, using exponentiation by squaring.
3059        ///
3060        /// # Examples
3061        ///
3062        /// Basic usage:
3063        ///
3064        /// ```
3065        #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".pow(5), 32);")]
3066        /// ```
3067        #[stable(feature = "rust1", since = "1.0.0")]
3068        #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
3069        #[must_use = "this returns the result of the operation, \
3070                      without modifying the original"]
3071        #[inline]
3072        #[rustc_inherit_overflow_checks]
3073        pub const fn pow(self, mut exp: u32) -> Self {
3074            if exp == 0 {
3075                return 1;
3076            }
3077            let mut base = self;
3078            let mut acc = 1;
3079
3080            if intrinsics::is_val_statically_known(exp) {
3081                while exp > 1 {
3082                    if (exp & 1) == 1 {
3083                        acc = acc * base;
3084                    }
3085                    exp /= 2;
3086                    base = base * base;
3087                }
3088
3089                // since exp!=0, finally the exp must be 1.
3090                // Deal with the final bit of the exponent separately, since
3091                // squaring the base afterwards is not necessary and may cause a
3092                // needless overflow.
3093                acc * base
3094            } else {
3095                // This is faster than the above when the exponent is not known
3096                // at compile time. We can't use the same code for the constant
3097                // exponent case because LLVM is currently unable to unroll
3098                // this loop.
3099                loop {
3100                    if (exp & 1) == 1 {
3101                        acc = acc * base;
3102                        // since exp!=0, finally the exp must be 1.
3103                        if exp == 1 {
3104                            return acc;
3105                        }
3106                    }
3107                    exp /= 2;
3108                    base = base * base;
3109                }
3110            }
3111        }
3112
3113        /// Returns the square root of the number, rounded down.
3114        ///
3115        /// # Examples
3116        ///
3117        /// Basic usage:
3118        /// ```
3119        #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".isqrt(), 3);")]
3120        /// ```
3121        #[stable(feature = "isqrt", since = "1.84.0")]
3122        #[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
3123        #[must_use = "this returns the result of the operation, \
3124                      without modifying the original"]
3125        #[inline]
3126        pub const fn isqrt(self) -> Self {
3127            let result = crate::num::int_sqrt::$ActualT(self as $ActualT) as $SelfT;
3128
3129            // Inform the optimizer what the range of outputs is. If testing
3130            // `core` crashes with no panic message and a `num::int_sqrt::u*`
3131            // test failed, it's because your edits caused these assertions or
3132            // the assertions in `fn isqrt` of `nonzero.rs` to become false.
3133            //
3134            // SAFETY: Integer square root is a monotonically nondecreasing
3135            // function, which means that increasing the input will never
3136            // cause the output to decrease. Thus, since the input for unsigned
3137            // integers is bounded by `[0, <$ActualT>::MAX]`, sqrt(n) will be
3138            // bounded by `[sqrt(0), sqrt(<$ActualT>::MAX)]`.
3139            unsafe {
3140                const MAX_RESULT: $SelfT = crate::num::int_sqrt::$ActualT(<$ActualT>::MAX) as $SelfT;
3141                crate::hint::assert_unchecked(result <= MAX_RESULT);
3142            }
3143
3144            result
3145        }
3146
3147        /// Performs Euclidean division.
3148        ///
3149        /// Since, for the positive integers, all common
3150        /// definitions of division are equal, this
3151        /// is exactly equal to `self / rhs`.
3152        ///
3153        /// # Panics
3154        ///
3155        /// This function will panic if `rhs` is zero.
3156        ///
3157        /// # Examples
3158        ///
3159        /// Basic usage:
3160        ///
3161        /// ```
3162        #[doc = concat!("assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type")]
3163        /// ```
3164        #[stable(feature = "euclidean_division", since = "1.38.0")]
3165        #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
3166        #[must_use = "this returns the result of the operation, \
3167                      without modifying the original"]
3168        #[inline(always)]
3169        #[track_caller]
3170        pub const fn div_euclid(self, rhs: Self) -> Self {
3171            self / rhs
3172        }
3173
3174
3175        /// Calculates the least remainder of `self (mod rhs)`.
3176        ///
3177        /// Since, for the positive integers, all common
3178        /// definitions of division are equal, this
3179        /// is exactly equal to `self % rhs`.
3180        ///
3181        /// # Panics
3182        ///
3183        /// This function will panic if `rhs` is zero.
3184        ///
3185        /// # Examples
3186        ///
3187        /// Basic usage:
3188        ///
3189        /// ```
3190        #[doc = concat!("assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type")]
3191        /// ```
3192        #[doc(alias = "modulo", alias = "mod")]
3193        #[stable(feature = "euclidean_division", since = "1.38.0")]
3194        #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
3195        #[must_use = "this returns the result of the operation, \
3196                      without modifying the original"]
3197        #[inline(always)]
3198        #[track_caller]
3199        pub const fn rem_euclid(self, rhs: Self) -> Self {
3200            self % rhs
3201        }
3202
3203        /// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
3204        ///
3205        /// This is the same as performing `self / rhs` for all unsigned integers.
3206        ///
3207        /// # Panics
3208        ///
3209        /// This function will panic if `rhs` is zero.
3210        ///
3211        /// # Examples
3212        ///
3213        /// Basic usage:
3214        ///
3215        /// ```
3216        /// #![feature(int_roundings)]
3217        #[doc = concat!("assert_eq!(7_", stringify!($SelfT), ".div_floor(4), 1);")]
3218        /// ```
3219        #[unstable(feature = "int_roundings", issue = "88581")]
3220        #[must_use = "this returns the result of the operation, \
3221                      without modifying the original"]
3222        #[inline(always)]
3223        #[track_caller]
3224        pub const fn div_floor(self, rhs: Self) -> Self {
3225            self / rhs
3226        }
3227
3228        /// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
3229        ///
3230        /// # Panics
3231        ///
3232        /// This function will panic if `rhs` is zero.
3233        ///
3234        /// # Examples
3235        ///
3236        /// Basic usage:
3237        ///
3238        /// ```
3239        #[doc = concat!("assert_eq!(7_", stringify!($SelfT), ".div_ceil(4), 2);")]
3240        /// ```
3241        #[stable(feature = "int_roundings1", since = "1.73.0")]
3242        #[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
3243        #[must_use = "this returns the result of the operation, \
3244                      without modifying the original"]
3245        #[inline]
3246        #[track_caller]
3247        pub const fn div_ceil(self, rhs: Self) -> Self {
3248            let d = self / rhs;
3249            let r = self % rhs;
3250            if r > 0 {
3251                d + 1
3252            } else {
3253                d
3254            }
3255        }
3256
3257        /// Calculates the smallest value greater than or equal to `self` that
3258        /// is a multiple of `rhs`.
3259        ///
3260        /// # Panics
3261        ///
3262        /// This function will panic if `rhs` is zero.
3263        ///
3264        /// ## Overflow behavior
3265        ///
3266        /// On overflow, this function will panic if overflow checks are enabled (default in debug
3267        /// mode) and wrap if overflow checks are disabled (default in release mode).
3268        ///
3269        /// # Examples
3270        ///
3271        /// Basic usage:
3272        ///
3273        /// ```
3274        #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".next_multiple_of(8), 16);")]
3275        #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".next_multiple_of(8), 24);")]
3276        /// ```
3277        #[stable(feature = "int_roundings1", since = "1.73.0")]
3278        #[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
3279        #[must_use = "this returns the result of the operation, \
3280                      without modifying the original"]
3281        #[inline]
3282        #[rustc_inherit_overflow_checks]
3283        pub const fn next_multiple_of(self, rhs: Self) -> Self {
3284            match self % rhs {
3285                0 => self,
3286                r => self + (rhs - r)
3287            }
3288        }
3289
3290        /// Calculates the smallest value greater than or equal to `self` that
3291        /// is a multiple of `rhs`. Returns `None` if `rhs` is zero or the
3292        /// operation would result in overflow.
3293        ///
3294        /// # Examples
3295        ///
3296        /// Basic usage:
3297        ///
3298        /// ```
3299        #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(16));")]
3300        #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(24));")]
3301        #[doc = concat!("assert_eq!(1_", stringify!($SelfT), ".checked_next_multiple_of(0), None);")]
3302        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_multiple_of(2), None);")]
3303        /// ```
3304        #[stable(feature = "int_roundings1", since = "1.73.0")]
3305        #[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
3306        #[must_use = "this returns the result of the operation, \
3307                      without modifying the original"]
3308        #[inline]
3309        pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
3310            match try_opt!(self.checked_rem(rhs)) {
3311                0 => Some(self),
3312                // rhs - r cannot overflow because r is smaller than rhs
3313                r => self.checked_add(rhs - r)
3314            }
3315        }
3316
3317        /// Returns `true` if `self` is an integer multiple of `rhs`, and false otherwise.
3318        ///
3319        /// This function is equivalent to `self % rhs == 0`, except that it will not panic
3320        /// for `rhs == 0`. Instead, `0.is_multiple_of(0) == true`, and for any non-zero `n`,
3321        /// `n.is_multiple_of(0) == false`.
3322        ///
3323        /// # Examples
3324        ///
3325        /// Basic usage:
3326        ///
3327        /// ```
3328        #[doc = concat!("assert!(6_", stringify!($SelfT), ".is_multiple_of(2));")]
3329        #[doc = concat!("assert!(!5_", stringify!($SelfT), ".is_multiple_of(2));")]
3330        ///
3331        #[doc = concat!("assert!(0_", stringify!($SelfT), ".is_multiple_of(0));")]
3332        #[doc = concat!("assert!(!6_", stringify!($SelfT), ".is_multiple_of(0));")]
3333        /// ```
3334        #[stable(feature = "unsigned_is_multiple_of", since = "CURRENT_RUSTC_VERSION")]
3335        #[rustc_const_stable(feature = "unsigned_is_multiple_of", since = "CURRENT_RUSTC_VERSION")]
3336        #[must_use]
3337        #[inline]
3338        #[rustc_inherit_overflow_checks]
3339        pub const fn is_multiple_of(self, rhs: Self) -> bool {
3340            match rhs {
3341                0 => self == 0,
3342                _ => self % rhs == 0,
3343            }
3344        }
3345
3346        /// Returns `true` if and only if `self == 2^k` for some `k`.
3347        ///
3348        /// # Examples
3349        ///
3350        /// Basic usage:
3351        ///
3352        /// ```
3353        #[doc = concat!("assert!(16", stringify!($SelfT), ".is_power_of_two());")]
3354        #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_power_of_two());")]
3355        /// ```
3356        #[must_use]
3357        #[stable(feature = "rust1", since = "1.0.0")]
3358        #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
3359        #[inline(always)]
3360        pub const fn is_power_of_two(self) -> bool {
3361            self.count_ones() == 1
3362        }
3363
3364        // Returns one less than next power of two.
3365        // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
3366        //
3367        // 8u8.one_less_than_next_power_of_two() == 7
3368        // 6u8.one_less_than_next_power_of_two() == 7
3369        //
3370        // This method cannot overflow, as in the `next_power_of_two`
3371        // overflow cases it instead ends up returning the maximum value
3372        // of the type, and can return 0 for 0.
3373        #[inline]
3374        const fn one_less_than_next_power_of_two(self) -> Self {
3375            if self <= 1 { return 0; }
3376
3377            let p = self - 1;
3378            // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros.
3379            // That means the shift is always in-bounds, and some processors
3380            // (such as intel pre-haswell) have more efficient ctlz
3381            // intrinsics when the argument is non-zero.
3382            let z = unsafe { intrinsics::ctlz_nonzero(p) };
3383            <$SelfT>::MAX >> z
3384        }
3385
3386        /// Returns the smallest power of two greater than or equal to `self`.
3387        ///
3388        /// When return value overflows (i.e., `self > (1 << (N-1))` for type
3389        /// `uN`), it panics in debug mode and the return value is wrapped to 0 in
3390        /// release mode (the only situation in which this method can return 0).
3391        ///
3392        /// # Examples
3393        ///
3394        /// Basic usage:
3395        ///
3396        /// ```
3397        #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);")]
3398        #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);")]
3399        #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".next_power_of_two(), 1);")]
3400        /// ```
3401        #[stable(feature = "rust1", since = "1.0.0")]
3402        #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
3403        #[must_use = "this returns the result of the operation, \
3404                      without modifying the original"]
3405        #[inline]
3406        #[rustc_inherit_overflow_checks]
3407        pub const fn next_power_of_two(self) -> Self {
3408            self.one_less_than_next_power_of_two() + 1
3409        }
3410
3411        /// Returns the smallest power of two greater than or equal to `self`. If
3412        /// the next power of two is greater than the type's maximum value,
3413        /// `None` is returned, otherwise the power of two is wrapped in `Some`.
3414        ///
3415        /// # Examples
3416        ///
3417        /// Basic usage:
3418        ///
3419        /// ```
3420        #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_next_power_of_two(), Some(2));")]
3421        #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));")]
3422        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_power_of_two(), None);")]
3423        /// ```
3424        #[inline]
3425        #[stable(feature = "rust1", since = "1.0.0")]
3426        #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
3427        #[must_use = "this returns the result of the operation, \
3428                      without modifying the original"]
3429        pub const fn checked_next_power_of_two(self) -> Option<Self> {
3430            self.one_less_than_next_power_of_two().checked_add(1)
3431        }
3432
3433        /// Returns the smallest power of two greater than or equal to `n`. If
3434        /// the next power of two is greater than the type's maximum value,
3435        /// the return value is wrapped to `0`.
3436        ///
3437        /// # Examples
3438        ///
3439        /// Basic usage:
3440        ///
3441        /// ```
3442        /// #![feature(wrapping_next_power_of_two)]
3443        ///
3444        #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);")]
3445        #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);")]
3446        #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_next_power_of_two(), 0);")]
3447        /// ```
3448        #[inline]
3449        #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
3450                   reason = "needs decision on wrapping behavior")]
3451        #[must_use = "this returns the result of the operation, \
3452                      without modifying the original"]
3453        pub const fn wrapping_next_power_of_two(self) -> Self {
3454            self.one_less_than_next_power_of_two().wrapping_add(1)
3455        }
3456
3457        /// Returns the memory representation of this integer as a byte array in
3458        /// big-endian (network) byte order.
3459        ///
3460        #[doc = $to_xe_bytes_doc]
3461        ///
3462        /// # Examples
3463        ///
3464        /// ```
3465        #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();")]
3466        #[doc = concat!("assert_eq!(bytes, ", $be_bytes, ");")]
3467        /// ```
3468        #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3469        #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3470        #[must_use = "this returns the result of the operation, \
3471                      without modifying the original"]
3472        #[inline]
3473        pub const fn to_be_bytes(self) -> [u8; size_of::<Self>()] {
3474            self.to_be().to_ne_bytes()
3475        }
3476
3477        /// Returns the memory representation of this integer as a byte array in
3478        /// little-endian byte order.
3479        ///
3480        #[doc = $to_xe_bytes_doc]
3481        ///
3482        /// # Examples
3483        ///
3484        /// ```
3485        #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();")]
3486        #[doc = concat!("assert_eq!(bytes, ", $le_bytes, ");")]
3487        /// ```
3488        #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3489        #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3490        #[must_use = "this returns the result of the operation, \
3491                      without modifying the original"]
3492        #[inline]
3493        pub const fn to_le_bytes(self) -> [u8; size_of::<Self>()] {
3494            self.to_le().to_ne_bytes()
3495        }
3496
3497        /// Returns the memory representation of this integer as a byte array in
3498        /// native byte order.
3499        ///
3500        /// As the target platform's native endianness is used, portable code
3501        /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
3502        /// instead.
3503        ///
3504        #[doc = $to_xe_bytes_doc]
3505        ///
3506        /// [`to_be_bytes`]: Self::to_be_bytes
3507        /// [`to_le_bytes`]: Self::to_le_bytes
3508        ///
3509        /// # Examples
3510        ///
3511        /// ```
3512        #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();")]
3513        /// assert_eq!(
3514        ///     bytes,
3515        ///     if cfg!(target_endian = "big") {
3516        #[doc = concat!("        ", $be_bytes)]
3517        ///     } else {
3518        #[doc = concat!("        ", $le_bytes)]
3519        ///     }
3520        /// );
3521        /// ```
3522        #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3523        #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3524        #[must_use = "this returns the result of the operation, \
3525                      without modifying the original"]
3526        // SAFETY: const sound because integers are plain old datatypes so we can always
3527        // transmute them to arrays of bytes
3528        #[inline]
3529        pub const fn to_ne_bytes(self) -> [u8; size_of::<Self>()] {
3530            // SAFETY: integers are plain old datatypes so we can always transmute them to
3531            // arrays of bytes
3532            unsafe { mem::transmute(self) }
3533        }
3534
3535        /// Creates a native endian integer value from its representation
3536        /// as a byte array in big endian.
3537        ///
3538        #[doc = $from_xe_bytes_doc]
3539        ///
3540        /// # Examples
3541        ///
3542        /// ```
3543        #[doc = concat!("let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");")]
3544        #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
3545        /// ```
3546        ///
3547        /// When starting from a slice rather than an array, fallible conversion APIs can be used:
3548        ///
3549        /// ```
3550        #[doc = concat!("fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
3551        #[doc = concat!("    let (int_bytes, rest) = input.split_at(size_of::<", stringify!($SelfT), ">());")]
3552        ///     *input = rest;
3553        #[doc = concat!("    ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())")]
3554        /// }
3555        /// ```
3556        #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3557        #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3558        #[must_use]
3559        #[inline]
3560        pub const fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
3561            Self::from_be(Self::from_ne_bytes(bytes))
3562        }
3563
3564        /// Creates a native endian integer value from its representation
3565        /// as a byte array in little endian.
3566        ///
3567        #[doc = $from_xe_bytes_doc]
3568        ///
3569        /// # Examples
3570        ///
3571        /// ```
3572        #[doc = concat!("let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");")]
3573        #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
3574        /// ```
3575        ///
3576        /// When starting from a slice rather than an array, fallible conversion APIs can be used:
3577        ///
3578        /// ```
3579        #[doc = concat!("fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
3580        #[doc = concat!("    let (int_bytes, rest) = input.split_at(size_of::<", stringify!($SelfT), ">());")]
3581        ///     *input = rest;
3582        #[doc = concat!("    ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())")]
3583        /// }
3584        /// ```
3585        #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3586        #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3587        #[must_use]
3588        #[inline]
3589        pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
3590            Self::from_le(Self::from_ne_bytes(bytes))
3591        }
3592
3593        /// Creates a native endian integer value from its memory representation
3594        /// as a byte array in native endianness.
3595        ///
3596        /// As the target platform's native endianness is used, portable code
3597        /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
3598        /// appropriate instead.
3599        ///
3600        /// [`from_be_bytes`]: Self::from_be_bytes
3601        /// [`from_le_bytes`]: Self::from_le_bytes
3602        ///
3603        #[doc = $from_xe_bytes_doc]
3604        ///
3605        /// # Examples
3606        ///
3607        /// ```
3608        #[doc = concat!("let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {")]
3609        #[doc = concat!("    ", $be_bytes, "")]
3610        /// } else {
3611        #[doc = concat!("    ", $le_bytes, "")]
3612        /// });
3613        #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
3614        /// ```
3615        ///
3616        /// When starting from a slice rather than an array, fallible conversion APIs can be used:
3617        ///
3618        /// ```
3619        #[doc = concat!("fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
3620        #[doc = concat!("    let (int_bytes, rest) = input.split_at(size_of::<", stringify!($SelfT), ">());")]
3621        ///     *input = rest;
3622        #[doc = concat!("    ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())")]
3623        /// }
3624        /// ```
3625        #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3626        #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3627        #[must_use]
3628        // SAFETY: const sound because integers are plain old datatypes so we can always
3629        // transmute to them
3630        #[inline]
3631        pub const fn from_ne_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
3632            // SAFETY: integers are plain old datatypes so we can always transmute to them
3633            unsafe { mem::transmute(bytes) }
3634        }
3635
3636        /// New code should prefer to use
3637        #[doc = concat!("[`", stringify!($SelfT), "::MIN", "`] instead.")]
3638        ///
3639        /// Returns the smallest value that can be represented by this integer type.
3640        #[stable(feature = "rust1", since = "1.0.0")]
3641        #[rustc_promotable]
3642        #[inline(always)]
3643        #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
3644        #[deprecated(since = "TBD", note = "replaced by the `MIN` associated constant on this type")]
3645        #[rustc_diagnostic_item = concat!(stringify!($SelfT), "_legacy_fn_min_value")]
3646        pub const fn min_value() -> Self { Self::MIN }
3647
3648        /// New code should prefer to use
3649        #[doc = concat!("[`", stringify!($SelfT), "::MAX", "`] instead.")]
3650        ///
3651        /// Returns the largest value that can be represented by this integer type.
3652        #[stable(feature = "rust1", since = "1.0.0")]
3653        #[rustc_promotable]
3654        #[inline(always)]
3655        #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
3656        #[deprecated(since = "TBD", note = "replaced by the `MAX` associated constant on this type")]
3657        #[rustc_diagnostic_item = concat!(stringify!($SelfT), "_legacy_fn_max_value")]
3658        pub const fn max_value() -> Self { Self::MAX }
3659    }
3660}