core/num/
int_macros.rs

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