Skip to main content

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