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