Skip to main content

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