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