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