Skip to main content

core/num/
uint_macros.rs

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