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