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