]> git.lizzy.rs Git - rust.git/blob - library/core/src/num/int_macros.rs
Auto merge of #95454 - randomicon00:fix95444, r=wesleywiser
[rust.git] / library / core / src / num / int_macros.rs
1 macro_rules! int_impl {
2     ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $BITS_MINUS_ONE:expr, $Min:expr, $Max:expr,
3      $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
4      $reversed:expr, $le_bytes:expr, $be_bytes:expr,
5      $to_xe_bytes_doc:expr, $from_xe_bytes_doc:expr) => {
6         /// The smallest value that can be represented by this integer type,
7         #[doc = concat!("&minus;2<sup>", $BITS_MINUS_ONE, "</sup>.")]
8         ///
9         /// # Examples
10         ///
11         /// Basic usage:
12         ///
13         /// ```
14         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN, ", stringify!($Min), ");")]
15         /// ```
16         #[stable(feature = "assoc_int_consts", since = "1.43.0")]
17         pub const MIN: Self = !0 ^ ((!0 as $UnsignedT) >> 1) as Self;
18
19         /// The largest value that can be represented by this integer type,
20         #[doc = concat!("2<sup>", $BITS_MINUS_ONE, "</sup> &minus; 1.")]
21         ///
22         /// # Examples
23         ///
24         /// Basic usage:
25         ///
26         /// ```
27         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($Max), ");")]
28         /// ```
29         #[stable(feature = "assoc_int_consts", since = "1.43.0")]
30         pub const MAX: Self = !Self::MIN;
31
32         /// The size of this integer type in bits.
33         ///
34         /// # Examples
35         ///
36         /// ```
37         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::BITS, ", stringify!($BITS), ");")]
38         /// ```
39         #[stable(feature = "int_bits_const", since = "1.53.0")]
40         pub const BITS: u32 = $BITS;
41
42         /// Converts a string slice in a given base to an integer.
43         ///
44         /// The string is expected to be an optional `+` or `-` sign followed by digits.
45         /// Leading and trailing whitespace represent an error. Digits are a subset of these characters,
46         /// depending on `radix`:
47         ///
48         ///  * `0-9`
49         ///  * `a-z`
50         ///  * `A-Z`
51         ///
52         /// # Panics
53         ///
54         /// This function panics if `radix` is not in the range from 2 to 36.
55         ///
56         /// # Examples
57         ///
58         /// Basic usage:
59         ///
60         /// ```
61         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));")]
62         /// ```
63         #[stable(feature = "rust1", since = "1.0.0")]
64         pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
65             from_str_radix(src, radix)
66         }
67
68         /// Returns the number of ones in the binary representation of `self`.
69         ///
70         /// # Examples
71         ///
72         /// Basic usage:
73         ///
74         /// ```
75         #[doc = concat!("let n = 0b100_0000", stringify!($SelfT), ";")]
76         ///
77         /// assert_eq!(n.count_ones(), 1);
78         /// ```
79         ///
80         #[stable(feature = "rust1", since = "1.0.0")]
81         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
82         #[doc(alias = "popcount")]
83         #[doc(alias = "popcnt")]
84         #[must_use = "this returns the result of the operation, \
85                       without modifying the original"]
86         #[inline(always)]
87         pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
88
89         /// Returns the number of zeros in the binary representation of `self`.
90         ///
91         /// # Examples
92         ///
93         /// Basic usage:
94         ///
95         /// ```
96         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.count_zeros(), 1);")]
97         /// ```
98         #[stable(feature = "rust1", since = "1.0.0")]
99         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
100         #[must_use = "this returns the result of the operation, \
101                       without modifying the original"]
102         #[inline(always)]
103         pub const fn count_zeros(self) -> u32 {
104             (!self).count_ones()
105         }
106
107         /// Returns the number of leading zeros in the binary representation of `self`.
108         ///
109         /// # Examples
110         ///
111         /// Basic usage:
112         ///
113         /// ```
114         #[doc = concat!("let n = -1", stringify!($SelfT), ";")]
115         ///
116         /// assert_eq!(n.leading_zeros(), 0);
117         /// ```
118         #[stable(feature = "rust1", since = "1.0.0")]
119         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
120         #[must_use = "this returns the result of the operation, \
121                       without modifying the original"]
122         #[inline(always)]
123         pub const fn leading_zeros(self) -> u32 {
124             (self as $UnsignedT).leading_zeros()
125         }
126
127         /// Returns the number of trailing zeros in the binary representation of `self`.
128         ///
129         /// # Examples
130         ///
131         /// Basic usage:
132         ///
133         /// ```
134         #[doc = concat!("let n = -4", stringify!($SelfT), ";")]
135         ///
136         /// assert_eq!(n.trailing_zeros(), 2);
137         /// ```
138         #[stable(feature = "rust1", since = "1.0.0")]
139         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
140         #[must_use = "this returns the result of the operation, \
141                       without modifying the original"]
142         #[inline(always)]
143         pub const fn trailing_zeros(self) -> u32 {
144             (self as $UnsignedT).trailing_zeros()
145         }
146
147         /// Returns the number of leading ones in the binary representation of `self`.
148         ///
149         /// # Examples
150         ///
151         /// Basic usage:
152         ///
153         /// ```
154         #[doc = concat!("let n = -1", stringify!($SelfT), ";")]
155         ///
156         #[doc = concat!("assert_eq!(n.leading_ones(), ", stringify!($BITS), ");")]
157         /// ```
158         #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
159         #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
160         #[must_use = "this returns the result of the operation, \
161                       without modifying the original"]
162         #[inline(always)]
163         pub const fn leading_ones(self) -> u32 {
164             (self as $UnsignedT).leading_ones()
165         }
166
167         /// Returns the number of trailing ones in the binary representation of `self`.
168         ///
169         /// # Examples
170         ///
171         /// Basic usage:
172         ///
173         /// ```
174         #[doc = concat!("let n = 3", stringify!($SelfT), ";")]
175         ///
176         /// assert_eq!(n.trailing_ones(), 2);
177         /// ```
178         #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
179         #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
180         #[must_use = "this returns the result of the operation, \
181                       without modifying the original"]
182         #[inline(always)]
183         pub const fn trailing_ones(self) -> u32 {
184             (self as $UnsignedT).trailing_ones()
185         }
186
187         /// Shifts the bits to the left by a specified amount, `n`,
188         /// wrapping the truncated bits to the end of the resulting integer.
189         ///
190         /// Please note this isn't the same operation as the `<<` shifting operator!
191         ///
192         /// # Examples
193         ///
194         /// Basic usage:
195         ///
196         /// ```
197         #[doc = concat!("let n = ", $rot_op, stringify!($SelfT), ";")]
198         #[doc = concat!("let m = ", $rot_result, ";")]
199         ///
200         #[doc = concat!("assert_eq!(n.rotate_left(", $rot, "), m);")]
201         /// ```
202         #[stable(feature = "rust1", since = "1.0.0")]
203         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
204         #[must_use = "this returns the result of the operation, \
205                       without modifying the original"]
206         #[inline(always)]
207         pub const fn rotate_left(self, n: u32) -> Self {
208             (self as $UnsignedT).rotate_left(n) as Self
209         }
210
211         /// Shifts the bits to the right by a specified amount, `n`,
212         /// wrapping the truncated bits to the beginning of the resulting
213         /// integer.
214         ///
215         /// Please note this isn't the same operation as the `>>` shifting operator!
216         ///
217         /// # Examples
218         ///
219         /// Basic usage:
220         ///
221         /// ```
222         #[doc = concat!("let n = ", $rot_result, stringify!($SelfT), ";")]
223         #[doc = concat!("let m = ", $rot_op, ";")]
224         ///
225         #[doc = concat!("assert_eq!(n.rotate_right(", $rot, "), m);")]
226         /// ```
227         #[stable(feature = "rust1", since = "1.0.0")]
228         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
229         #[must_use = "this returns the result of the operation, \
230                       without modifying the original"]
231         #[inline(always)]
232         pub const fn rotate_right(self, n: u32) -> Self {
233             (self as $UnsignedT).rotate_right(n) as Self
234         }
235
236         /// Reverses the byte order of the integer.
237         ///
238         /// # Examples
239         ///
240         /// Basic usage:
241         ///
242         /// ```
243         #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
244         ///
245         /// let m = n.swap_bytes();
246         ///
247         #[doc = concat!("assert_eq!(m, ", $swapped, ");")]
248         /// ```
249         #[stable(feature = "rust1", since = "1.0.0")]
250         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
251         #[must_use = "this returns the result of the operation, \
252                       without modifying the original"]
253         #[inline(always)]
254         pub const fn swap_bytes(self) -> Self {
255             (self as $UnsignedT).swap_bytes() as Self
256         }
257
258         /// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
259         ///                 second least-significant bit becomes second most-significant bit, etc.
260         ///
261         /// # Examples
262         ///
263         /// Basic usage:
264         ///
265         /// ```
266         #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
267         /// let m = n.reverse_bits();
268         ///
269         #[doc = concat!("assert_eq!(m, ", $reversed, ");")]
270         #[doc = concat!("assert_eq!(0, 0", stringify!($SelfT), ".reverse_bits());")]
271         /// ```
272         #[stable(feature = "reverse_bits", since = "1.37.0")]
273         #[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
274         #[must_use = "this returns the result of the operation, \
275                       without modifying the original"]
276         #[inline(always)]
277         pub const fn reverse_bits(self) -> Self {
278             (self as $UnsignedT).reverse_bits() as Self
279         }
280
281         /// Converts an integer from big endian to the target's endianness.
282         ///
283         /// On big endian this is a no-op. On little endian the bytes are swapped.
284         ///
285         /// # Examples
286         ///
287         /// Basic usage:
288         ///
289         /// ```
290         #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
291         ///
292         /// if cfg!(target_endian = "big") {
293         #[doc = concat!("    assert_eq!(", stringify!($SelfT), "::from_be(n), n)")]
294         /// } else {
295         #[doc = concat!("    assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())")]
296         /// }
297         /// ```
298         #[stable(feature = "rust1", since = "1.0.0")]
299         #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
300         #[must_use]
301         #[inline]
302         pub const fn from_be(x: Self) -> Self {
303             #[cfg(target_endian = "big")]
304             {
305                 x
306             }
307             #[cfg(not(target_endian = "big"))]
308             {
309                 x.swap_bytes()
310             }
311         }
312
313         /// Converts an integer from little endian to the target's endianness.
314         ///
315         /// On little endian this is a no-op. On big endian the bytes are swapped.
316         ///
317         /// # Examples
318         ///
319         /// Basic usage:
320         ///
321         /// ```
322         #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
323         ///
324         /// if cfg!(target_endian = "little") {
325         #[doc = concat!("    assert_eq!(", stringify!($SelfT), "::from_le(n), n)")]
326         /// } else {
327         #[doc = concat!("    assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())")]
328         /// }
329         /// ```
330         #[stable(feature = "rust1", since = "1.0.0")]
331         #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
332         #[must_use]
333         #[inline]
334         pub const fn from_le(x: Self) -> Self {
335             #[cfg(target_endian = "little")]
336             {
337                 x
338             }
339             #[cfg(not(target_endian = "little"))]
340             {
341                 x.swap_bytes()
342             }
343         }
344
345         /// Converts `self` to big endian from the target's endianness.
346         ///
347         /// On big endian this is a no-op. On little endian the bytes are swapped.
348         ///
349         /// # Examples
350         ///
351         /// Basic usage:
352         ///
353         /// ```
354         #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
355         ///
356         /// if cfg!(target_endian = "big") {
357         ///     assert_eq!(n.to_be(), n)
358         /// } else {
359         ///     assert_eq!(n.to_be(), n.swap_bytes())
360         /// }
361         /// ```
362         #[stable(feature = "rust1", since = "1.0.0")]
363         #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
364         #[must_use = "this returns the result of the operation, \
365                       without modifying the original"]
366         #[inline]
367         pub const fn to_be(self) -> Self { // or not to be?
368             #[cfg(target_endian = "big")]
369             {
370                 self
371             }
372             #[cfg(not(target_endian = "big"))]
373             {
374                 self.swap_bytes()
375             }
376         }
377
378         /// Converts `self` to little endian from the target's endianness.
379         ///
380         /// On little endian this is a no-op. On big endian the bytes are swapped.
381         ///
382         /// # Examples
383         ///
384         /// Basic usage:
385         ///
386         /// ```
387         #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
388         ///
389         /// if cfg!(target_endian = "little") {
390         ///     assert_eq!(n.to_le(), n)
391         /// } else {
392         ///     assert_eq!(n.to_le(), n.swap_bytes())
393         /// }
394         /// ```
395         #[stable(feature = "rust1", since = "1.0.0")]
396         #[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
397         #[must_use = "this returns the result of the operation, \
398                       without modifying the original"]
399         #[inline]
400         pub const fn to_le(self) -> Self {
401             #[cfg(target_endian = "little")]
402             {
403                 self
404             }
405             #[cfg(not(target_endian = "little"))]
406             {
407                 self.swap_bytes()
408             }
409         }
410
411         /// Checked integer addition. Computes `self + rhs`, returning `None`
412         /// if overflow occurred.
413         ///
414         /// # Examples
415         ///
416         /// Basic usage:
417         ///
418         /// ```
419         #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(1), Some(", stringify!($SelfT), "::MAX - 1));")]
420         #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);")]
421         /// ```
422         #[stable(feature = "rust1", since = "1.0.0")]
423         #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
424         #[must_use = "this returns the result of the operation, \
425                       without modifying the original"]
426         #[inline]
427         pub const fn checked_add(self, rhs: Self) -> Option<Self> {
428             let (a, b) = self.overflowing_add(rhs);
429             if unlikely!(b) {None} else {Some(a)}
430         }
431
432         /// Unchecked integer addition. Computes `self + rhs`, assuming overflow
433         /// cannot occur.
434         ///
435         /// # Safety
436         ///
437         /// This results in undefined behavior when
438         #[doc = concat!("`self + rhs > ", stringify!($SelfT), "::MAX` or `self + rhs < ", stringify!($SelfT), "::MIN`,")]
439         /// i.e. when [`checked_add`] would return `None`.
440         ///
441         #[doc = concat!("[`checked_add`]: ", stringify!($SelfT), "::checked_add")]
442         #[unstable(
443             feature = "unchecked_math",
444             reason = "niche optimization path",
445             issue = "85122",
446         )]
447         #[must_use = "this returns the result of the operation, \
448                       without modifying the original"]
449         #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
450         #[inline(always)]
451         pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
452             // SAFETY: the caller must uphold the safety contract for
453             // `unchecked_add`.
454             unsafe { intrinsics::unchecked_add(self, rhs) }
455         }
456
457         /// Checked addition with an unsigned integer. Computes `self + rhs`,
458         /// returning `None` if overflow occurred.
459         ///
460         /// # Examples
461         ///
462         /// Basic usage:
463         ///
464         /// ```
465         /// # #![feature(mixed_integer_ops)]
466         #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_add_unsigned(2), Some(3));")]
467         #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add_unsigned(3), None);")]
468         /// ```
469         #[unstable(feature = "mixed_integer_ops", issue = "87840")]
470         #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
471         #[must_use = "this returns the result of the operation, \
472                       without modifying the original"]
473         #[inline]
474         pub const fn checked_add_unsigned(self, rhs: $UnsignedT) -> Option<Self> {
475             let (a, b) = self.overflowing_add_unsigned(rhs);
476             if unlikely!(b) {None} else {Some(a)}
477         }
478
479         /// Checked integer subtraction. Computes `self - rhs`, returning `None` if
480         /// overflow occurred.
481         ///
482         /// # Examples
483         ///
484         /// Basic usage:
485         ///
486         /// ```
487         #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 2).checked_sub(1), Some(", stringify!($SelfT), "::MIN + 1));")]
488         #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 2).checked_sub(3), None);")]
489         /// ```
490         #[stable(feature = "rust1", since = "1.0.0")]
491         #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
492         #[must_use = "this returns the result of the operation, \
493                       without modifying the original"]
494         #[inline]
495         pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
496             let (a, b) = self.overflowing_sub(rhs);
497             if unlikely!(b) {None} else {Some(a)}
498         }
499
500         /// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
501         /// cannot occur.
502         ///
503         /// # Safety
504         ///
505         /// This results in undefined behavior when
506         #[doc = concat!("`self - rhs > ", stringify!($SelfT), "::MAX` or `self - rhs < ", stringify!($SelfT), "::MIN`,")]
507         /// i.e. when [`checked_sub`] would return `None`.
508         ///
509         #[doc = concat!("[`checked_sub`]: ", stringify!($SelfT), "::checked_sub")]
510         #[unstable(
511             feature = "unchecked_math",
512             reason = "niche optimization path",
513             issue = "85122",
514         )]
515         #[must_use = "this returns the result of the operation, \
516                       without modifying the original"]
517         #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
518         #[inline(always)]
519         pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
520             // SAFETY: the caller must uphold the safety contract for
521             // `unchecked_sub`.
522             unsafe { intrinsics::unchecked_sub(self, rhs) }
523         }
524
525         /// Checked subtraction with an unsigned integer. Computes `self - rhs`,
526         /// returning `None` if overflow occurred.
527         ///
528         /// # Examples
529         ///
530         /// Basic usage:
531         ///
532         /// ```
533         /// # #![feature(mixed_integer_ops)]
534         #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_sub_unsigned(2), Some(-1));")]
535         #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 2).checked_sub_unsigned(3), None);")]
536         /// ```
537         #[unstable(feature = "mixed_integer_ops", issue = "87840")]
538         #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
539         #[must_use = "this returns the result of the operation, \
540                       without modifying the original"]
541         #[inline]
542         pub const fn checked_sub_unsigned(self, rhs: $UnsignedT) -> Option<Self> {
543             let (a, b) = self.overflowing_sub_unsigned(rhs);
544             if unlikely!(b) {None} else {Some(a)}
545         }
546
547         /// Checked integer multiplication. Computes `self * rhs`, returning `None` if
548         /// overflow occurred.
549         ///
550         /// # Examples
551         ///
552         /// Basic usage:
553         ///
554         /// ```
555         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(1), Some(", stringify!($SelfT), "::MAX));")]
556         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);")]
557         /// ```
558         #[stable(feature = "rust1", since = "1.0.0")]
559         #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
560         #[must_use = "this returns the result of the operation, \
561                       without modifying the original"]
562         #[inline]
563         pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
564             let (a, b) = self.overflowing_mul(rhs);
565             if unlikely!(b) {None} else {Some(a)}
566         }
567
568         /// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
569         /// cannot occur.
570         ///
571         /// # Safety
572         ///
573         /// This results in undefined behavior when
574         #[doc = concat!("`self * rhs > ", stringify!($SelfT), "::MAX` or `self * rhs < ", stringify!($SelfT), "::MIN`,")]
575         /// i.e. when [`checked_mul`] would return `None`.
576         ///
577         #[doc = concat!("[`checked_mul`]: ", stringify!($SelfT), "::checked_mul")]
578         #[unstable(
579             feature = "unchecked_math",
580             reason = "niche optimization path",
581             issue = "85122",
582         )]
583         #[must_use = "this returns the result of the operation, \
584                       without modifying the original"]
585         #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
586         #[inline(always)]
587         pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
588             // SAFETY: the caller must uphold the safety contract for
589             // `unchecked_mul`.
590             unsafe { intrinsics::unchecked_mul(self, rhs) }
591         }
592
593         /// Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
594         /// or the division results in overflow.
595         ///
596         /// # Examples
597         ///
598         /// Basic usage:
599         ///
600         /// ```
601         #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 1).checked_div(-1), Some(", stringify!($Max), "));")]
602         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_div(-1), None);")]
603         #[doc = concat!("assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);")]
604         /// ```
605         #[stable(feature = "rust1", since = "1.0.0")]
606         #[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
607         #[must_use = "this returns the result of the operation, \
608                       without modifying the original"]
609         #[inline]
610         pub const fn checked_div(self, rhs: Self) -> Option<Self> {
611             if unlikely!(rhs == 0 || ((self == Self::MIN) && (rhs == -1))) {
612                 None
613             } else {
614                 // SAFETY: div by zero and by INT_MIN have been checked above
615                 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
616             }
617         }
618
619         /// Checked Euclidean division. Computes `self.div_euclid(rhs)`,
620         /// returning `None` if `rhs == 0` or the division results in overflow.
621         ///
622         /// # Examples
623         ///
624         /// Basic usage:
625         ///
626         /// ```
627         #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 1).checked_div_euclid(-1), Some(", stringify!($Max), "));")]
628         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_div_euclid(-1), None);")]
629         #[doc = concat!("assert_eq!((1", stringify!($SelfT), ").checked_div_euclid(0), None);")]
630         /// ```
631         #[stable(feature = "euclidean_division", since = "1.38.0")]
632         #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
633         #[must_use = "this returns the result of the operation, \
634                       without modifying the original"]
635         #[inline]
636         pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
637             // Using `&` helps LLVM see that it is the same check made in division.
638             if unlikely!(rhs == 0 || ((self == Self::MIN) & (rhs == -1))) {
639                 None
640             } else {
641                 Some(self.div_euclid(rhs))
642             }
643         }
644
645         /// Checked integer remainder. Computes `self % rhs`, returning `None` if
646         /// `rhs == 0` or the division results in overflow.
647         ///
648         /// # Examples
649         ///
650         /// Basic usage:
651         ///
652         /// ```
653         ///
654         #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));")]
655         #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);")]
656         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);")]
657         /// ```
658         #[stable(feature = "wrapping", since = "1.7.0")]
659         #[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
660         #[must_use = "this returns the result of the operation, \
661                       without modifying the original"]
662         #[inline]
663         pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
664             if unlikely!(rhs == 0 || ((self == Self::MIN) && (rhs == -1))) {
665                 None
666             } else {
667                 // SAFETY: div by zero and by INT_MIN have been checked above
668                 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
669             }
670         }
671
672         /// Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`
673         /// if `rhs == 0` or the division results in overflow.
674         ///
675         /// # Examples
676         ///
677         /// Basic usage:
678         ///
679         /// ```
680         #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));")]
681         #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);")]
682         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_rem_euclid(-1), None);")]
683         /// ```
684         #[stable(feature = "euclidean_division", since = "1.38.0")]
685         #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
686         #[must_use = "this returns the result of the operation, \
687                       without modifying the original"]
688         #[inline]
689         pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
690             // Using `&` helps LLVM see that it is the same check made in division.
691             if unlikely!(rhs == 0 || ((self == Self::MIN) & (rhs == -1))) {
692                 None
693             } else {
694                 Some(self.rem_euclid(rhs))
695             }
696         }
697
698         /// Checked negation. Computes `-self`, returning `None` if `self == MIN`.
699         ///
700         /// # Examples
701         ///
702         /// Basic usage:
703         ///
704         /// ```
705         ///
706         #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));")]
707         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);")]
708         /// ```
709         #[stable(feature = "wrapping", since = "1.7.0")]
710         #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
711         #[must_use = "this returns the result of the operation, \
712                       without modifying the original"]
713         #[inline]
714         pub const fn checked_neg(self) -> Option<Self> {
715             let (a, b) = self.overflowing_neg();
716             if unlikely!(b) {None} else {Some(a)}
717         }
718
719         /// Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
720         /// than or equal to the number of bits in `self`.
721         ///
722         /// # Examples
723         ///
724         /// Basic usage:
725         ///
726         /// ```
727         #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));")]
728         #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);")]
729         /// ```
730         #[stable(feature = "wrapping", since = "1.7.0")]
731         #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
732         #[must_use = "this returns the result of the operation, \
733                       without modifying the original"]
734         #[inline]
735         pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
736             let (a, b) = self.overflowing_shl(rhs);
737             if unlikely!(b) {None} else {Some(a)}
738         }
739
740         /// Unchecked shift left. Computes `self << rhs`, assuming that
741         /// `rhs` is less than the number of bits in `self`.
742         ///
743         /// # Safety
744         ///
745         /// This results in undefined behavior if `rhs` is larger than
746         /// or equal to the number of bits in `self`,
747         /// i.e. when [`checked_shl`] would return `None`.
748         ///
749         #[doc = concat!("[`checked_shl`]: ", stringify!($SelfT), "::checked_shl")]
750         #[unstable(
751             feature = "unchecked_math",
752             reason = "niche optimization path",
753             issue = "85122",
754         )]
755         #[must_use = "this returns the result of the operation, \
756                       without modifying the original"]
757         #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
758         #[inline(always)]
759         pub const unsafe fn unchecked_shl(self, rhs: Self) -> Self {
760             // SAFETY: the caller must uphold the safety contract for
761             // `unchecked_shl`.
762             unsafe { intrinsics::unchecked_shl(self, rhs) }
763         }
764
765         /// Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
766         /// larger than or equal to the number of bits in `self`.
767         ///
768         /// # Examples
769         ///
770         /// Basic usage:
771         ///
772         /// ```
773         #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));")]
774         #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);")]
775         /// ```
776         #[stable(feature = "wrapping", since = "1.7.0")]
777         #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
778         #[must_use = "this returns the result of the operation, \
779                       without modifying the original"]
780         #[inline]
781         pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
782             let (a, b) = self.overflowing_shr(rhs);
783             if unlikely!(b) {None} else {Some(a)}
784         }
785
786         /// Unchecked shift right. Computes `self >> rhs`, assuming that
787         /// `rhs` is less than the number of bits in `self`.
788         ///
789         /// # Safety
790         ///
791         /// This results in undefined behavior if `rhs` is larger than
792         /// or equal to the number of bits in `self`,
793         /// i.e. when [`checked_shr`] would return `None`.
794         ///
795         #[doc = concat!("[`checked_shr`]: ", stringify!($SelfT), "::checked_shr")]
796         #[unstable(
797             feature = "unchecked_math",
798             reason = "niche optimization path",
799             issue = "85122",
800         )]
801         #[must_use = "this returns the result of the operation, \
802                       without modifying the original"]
803         #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")]
804         #[inline(always)]
805         pub const unsafe fn unchecked_shr(self, rhs: Self) -> Self {
806             // SAFETY: the caller must uphold the safety contract for
807             // `unchecked_shr`.
808             unsafe { intrinsics::unchecked_shr(self, rhs) }
809         }
810
811         /// Checked absolute value. Computes `self.abs()`, returning `None` if
812         /// `self == MIN`.
813         ///
814         /// # Examples
815         ///
816         /// Basic usage:
817         ///
818         /// ```
819         ///
820         #[doc = concat!("assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));")]
821         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);")]
822         /// ```
823         #[stable(feature = "no_panic_abs", since = "1.13.0")]
824         #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
825         #[must_use = "this returns the result of the operation, \
826                       without modifying the original"]
827         #[inline]
828         pub const fn checked_abs(self) -> Option<Self> {
829             if self.is_negative() {
830                 self.checked_neg()
831             } else {
832                 Some(self)
833             }
834         }
835
836         /// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
837         /// overflow occurred.
838         ///
839         /// # Examples
840         ///
841         /// Basic usage:
842         ///
843         /// ```
844         #[doc = concat!("assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));")]
845         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);")]
846         /// ```
847
848         #[stable(feature = "no_panic_pow", since = "1.34.0")]
849         #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
850         #[must_use = "this returns the result of the operation, \
851                       without modifying the original"]
852         #[inline]
853         pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
854             if exp == 0 {
855                 return Some(1);
856             }
857             let mut base = self;
858             let mut acc: Self = 1;
859
860             while exp > 1 {
861                 if (exp & 1) == 1 {
862                     acc = try_opt!(acc.checked_mul(base));
863                 }
864                 exp /= 2;
865                 base = try_opt!(base.checked_mul(base));
866             }
867             // since exp!=0, finally the exp must be 1.
868             // Deal with the final bit of the exponent separately, since
869             // squaring the base afterwards is not necessary and may cause a
870             // needless overflow.
871             Some(try_opt!(acc.checked_mul(base)))
872         }
873
874         /// Saturating integer addition. Computes `self + rhs`, saturating at the numeric
875         /// bounds instead of overflowing.
876         ///
877         /// # Examples
878         ///
879         /// Basic usage:
880         ///
881         /// ```
882         #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);")]
883         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(100), ", stringify!($SelfT), "::MAX);")]
884         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_add(-1), ", stringify!($SelfT), "::MIN);")]
885         /// ```
886
887         #[stable(feature = "rust1", since = "1.0.0")]
888         #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
889         #[must_use = "this returns the result of the operation, \
890                       without modifying the original"]
891         #[inline(always)]
892         pub const fn saturating_add(self, rhs: Self) -> Self {
893             intrinsics::saturating_add(self, rhs)
894         }
895
896         /// Saturating addition with an unsigned integer. Computes `self + rhs`,
897         /// saturating at the numeric bounds instead of overflowing.
898         ///
899         /// # Examples
900         ///
901         /// Basic usage:
902         ///
903         /// ```
904         /// # #![feature(mixed_integer_ops)]
905         #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_unsigned(2), 3);")]
906         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add_unsigned(100), ", stringify!($SelfT), "::MAX);")]
907         /// ```
908         #[unstable(feature = "mixed_integer_ops", issue = "87840")]
909         #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
910         #[must_use = "this returns the result of the operation, \
911                       without modifying the original"]
912         #[inline]
913         pub const fn saturating_add_unsigned(self, rhs: $UnsignedT) -> Self {
914             // Overflow can only happen at the upper bound
915             // We cannot use `unwrap_or` here because it is not `const`
916             match self.checked_add_unsigned(rhs) {
917                 Some(x) => x,
918                 None => Self::MAX,
919             }
920         }
921
922         /// Saturating integer subtraction. Computes `self - rhs`, saturating at the
923         /// numeric bounds instead of overflowing.
924         ///
925         /// # Examples
926         ///
927         /// Basic usage:
928         ///
929         /// ```
930         #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);")]
931         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_sub(100), ", stringify!($SelfT), "::MIN);")]
932         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_sub(-1), ", stringify!($SelfT), "::MAX);")]
933         /// ```
934         #[stable(feature = "rust1", since = "1.0.0")]
935         #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
936         #[must_use = "this returns the result of the operation, \
937                       without modifying the original"]
938         #[inline(always)]
939         pub const fn saturating_sub(self, rhs: Self) -> Self {
940             intrinsics::saturating_sub(self, rhs)
941         }
942
943         /// Saturating subtraction with an unsigned integer. Computes `self - rhs`,
944         /// saturating at the numeric bounds instead of overflowing.
945         ///
946         /// # Examples
947         ///
948         /// Basic usage:
949         ///
950         /// ```
951         /// # #![feature(mixed_integer_ops)]
952         #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_sub_unsigned(127), -27);")]
953         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_sub_unsigned(100), ", stringify!($SelfT), "::MIN);")]
954         /// ```
955         #[unstable(feature = "mixed_integer_ops", issue = "87840")]
956         #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
957         #[must_use = "this returns the result of the operation, \
958                       without modifying the original"]
959         #[inline]
960         pub const fn saturating_sub_unsigned(self, rhs: $UnsignedT) -> Self {
961             // Overflow can only happen at the lower bound
962             // We cannot use `unwrap_or` here because it is not `const`
963             match self.checked_sub_unsigned(rhs) {
964                 Some(x) => x,
965                 None => Self::MIN,
966             }
967         }
968
969         /// Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
970         /// instead of overflowing.
971         ///
972         /// # Examples
973         ///
974         /// Basic usage:
975         ///
976         /// ```
977         #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_neg(), -100);")]
978         #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").saturating_neg(), 100);")]
979         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_neg(), ", stringify!($SelfT), "::MAX);")]
980         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_neg(), ", stringify!($SelfT), "::MIN + 1);")]
981         /// ```
982
983         #[stable(feature = "saturating_neg", since = "1.45.0")]
984         #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
985         #[must_use = "this returns the result of the operation, \
986                       without modifying the original"]
987         #[inline(always)]
988         pub const fn saturating_neg(self) -> Self {
989             intrinsics::saturating_sub(0, self)
990         }
991
992         /// Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
993         /// MIN` instead of overflowing.
994         ///
995         /// # Examples
996         ///
997         /// Basic usage:
998         ///
999         /// ```
1000         #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_abs(), 100);")]
1001         #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").saturating_abs(), 100);")]
1002         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_abs(), ", stringify!($SelfT), "::MAX);")]
1003         #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 1).saturating_abs(), ", stringify!($SelfT), "::MAX);")]
1004         /// ```
1005
1006         #[stable(feature = "saturating_neg", since = "1.45.0")]
1007         #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1008         #[must_use = "this returns the result of the operation, \
1009                       without modifying the original"]
1010         #[inline]
1011         pub const fn saturating_abs(self) -> Self {
1012             if self.is_negative() {
1013                 self.saturating_neg()
1014             } else {
1015                 self
1016             }
1017         }
1018
1019         /// Saturating integer multiplication. Computes `self * rhs`, saturating at the
1020         /// numeric bounds instead of overflowing.
1021         ///
1022         /// # Examples
1023         ///
1024         /// Basic usage:
1025         ///
1026         /// ```
1027         ///
1028         #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);")]
1029         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);")]
1030         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);")]
1031         /// ```
1032         #[stable(feature = "wrapping", since = "1.7.0")]
1033         #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1034         #[must_use = "this returns the result of the operation, \
1035                       without modifying the original"]
1036         #[inline]
1037         pub const fn saturating_mul(self, rhs: Self) -> Self {
1038             match self.checked_mul(rhs) {
1039                 Some(x) => x,
1040                 None => if (self < 0) == (rhs < 0) {
1041                     Self::MAX
1042                 } else {
1043                     Self::MIN
1044                 }
1045             }
1046         }
1047
1048         /// Saturating integer division. Computes `self / rhs`, saturating at the
1049         /// numeric bounds instead of overflowing.
1050         ///
1051         /// # Examples
1052         ///
1053         /// Basic usage:
1054         ///
1055         /// ```
1056         #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".saturating_div(2), 2);")]
1057         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_div(-1), ", stringify!($SelfT), "::MIN + 1);")]
1058         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_div(-1), ", stringify!($SelfT), "::MAX);")]
1059         ///
1060         /// ```
1061         ///
1062         /// ```should_panic
1063         #[doc = concat!("let _ = 1", stringify!($SelfT), ".saturating_div(0);")]
1064         ///
1065         /// ```
1066         #[stable(feature = "saturating_div", since = "1.58.0")]
1067         #[rustc_const_stable(feature = "saturating_div", since = "1.58.0")]
1068         #[must_use = "this returns the result of the operation, \
1069                       without modifying the original"]
1070         #[inline]
1071         pub const fn saturating_div(self, rhs: Self) -> Self {
1072             match self.overflowing_div(rhs) {
1073                 (result, false) => result,
1074                 (_result, true) => Self::MAX, // MIN / -1 is the only possible saturating overflow
1075             }
1076         }
1077
1078         /// Saturating integer exponentiation. Computes `self.pow(exp)`,
1079         /// saturating at the numeric bounds instead of overflowing.
1080         ///
1081         /// # Examples
1082         ///
1083         /// Basic usage:
1084         ///
1085         /// ```
1086         ///
1087         #[doc = concat!("assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);")]
1088         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);")]
1089         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);")]
1090         /// ```
1091         #[stable(feature = "no_panic_pow", since = "1.34.0")]
1092         #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1093         #[must_use = "this returns the result of the operation, \
1094                       without modifying the original"]
1095         #[inline]
1096         pub const fn saturating_pow(self, exp: u32) -> Self {
1097             match self.checked_pow(exp) {
1098                 Some(x) => x,
1099                 None if self < 0 && exp % 2 == 1 => Self::MIN,
1100                 None => Self::MAX,
1101             }
1102         }
1103
1104         /// Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
1105         /// boundary of the type.
1106         ///
1107         /// # Examples
1108         ///
1109         /// Basic usage:
1110         ///
1111         /// ```
1112         #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);")]
1113         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_add(2), ", stringify!($SelfT), "::MIN + 1);")]
1114         /// ```
1115         #[stable(feature = "rust1", since = "1.0.0")]
1116         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1117         #[must_use = "this returns the result of the operation, \
1118                       without modifying the original"]
1119         #[inline(always)]
1120         pub const fn wrapping_add(self, rhs: Self) -> Self {
1121             intrinsics::wrapping_add(self, rhs)
1122         }
1123
1124         /// Wrapping (modular) addition with an unsigned integer. Computes
1125         /// `self + rhs`, wrapping around at the boundary of the type.
1126         ///
1127         /// # Examples
1128         ///
1129         /// Basic usage:
1130         ///
1131         /// ```
1132         /// # #![feature(mixed_integer_ops)]
1133         #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_add_unsigned(27), 127);")]
1134         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_add_unsigned(2), ", stringify!($SelfT), "::MIN + 1);")]
1135         /// ```
1136         #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1137         #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1138         #[must_use = "this returns the result of the operation, \
1139                       without modifying the original"]
1140         #[inline(always)]
1141         pub const fn wrapping_add_unsigned(self, rhs: $UnsignedT) -> Self {
1142             self.wrapping_add(rhs as Self)
1143         }
1144
1145         /// Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1146         /// boundary of the type.
1147         ///
1148         /// # Examples
1149         ///
1150         /// Basic usage:
1151         ///
1152         /// ```
1153         #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);")]
1154         #[doc = concat!("assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::MAX), ", stringify!($SelfT), "::MAX);")]
1155         /// ```
1156         #[stable(feature = "rust1", since = "1.0.0")]
1157         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1158         #[must_use = "this returns the result of the operation, \
1159                       without modifying the original"]
1160         #[inline(always)]
1161         pub const fn wrapping_sub(self, rhs: Self) -> Self {
1162             intrinsics::wrapping_sub(self, rhs)
1163         }
1164
1165         /// Wrapping (modular) subtraction with an unsigned integer. Computes
1166         /// `self - rhs`, wrapping around at the boundary of the type.
1167         ///
1168         /// # Examples
1169         ///
1170         /// Basic usage:
1171         ///
1172         /// ```
1173         /// # #![feature(mixed_integer_ops)]
1174         #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".wrapping_sub_unsigned(127), -127);")]
1175         #[doc = concat!("assert_eq!((-2", stringify!($SelfT), ").wrapping_sub_unsigned(", stringify!($UnsignedT), "::MAX), -1);")]
1176         /// ```
1177         #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1178         #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1179         #[must_use = "this returns the result of the operation, \
1180                       without modifying the original"]
1181         #[inline(always)]
1182         pub const fn wrapping_sub_unsigned(self, rhs: $UnsignedT) -> Self {
1183             self.wrapping_sub(rhs as Self)
1184         }
1185
1186         /// Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1187         /// the boundary of the type.
1188         ///
1189         /// # Examples
1190         ///
1191         /// Basic usage:
1192         ///
1193         /// ```
1194         #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);")]
1195         /// assert_eq!(11i8.wrapping_mul(12), -124);
1196         /// ```
1197         #[stable(feature = "rust1", since = "1.0.0")]
1198         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1199         #[must_use = "this returns the result of the operation, \
1200                       without modifying the original"]
1201         #[inline(always)]
1202         pub const fn wrapping_mul(self, rhs: Self) -> Self {
1203             intrinsics::wrapping_mul(self, rhs)
1204         }
1205
1206         /// Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1207         /// boundary of the type.
1208         ///
1209         /// The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1210         /// `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1211         /// that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1212         ///
1213         /// # Panics
1214         ///
1215         /// This function will panic if `rhs` is 0.
1216         ///
1217         /// # Examples
1218         ///
1219         /// Basic usage:
1220         ///
1221         /// ```
1222         #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);")]
1223         /// assert_eq!((-128i8).wrapping_div(-1), -128);
1224         /// ```
1225         #[stable(feature = "num_wrapping", since = "1.2.0")]
1226         #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1227         #[must_use = "this returns the result of the operation, \
1228                       without modifying the original"]
1229         #[inline]
1230         pub const fn wrapping_div(self, rhs: Self) -> Self {
1231             self.overflowing_div(rhs).0
1232         }
1233
1234         /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
1235         /// wrapping around at the boundary of the type.
1236         ///
1237         /// Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1238         /// for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1239         /// type. In this case, this method returns `MIN` itself.
1240         ///
1241         /// # Panics
1242         ///
1243         /// This function will panic if `rhs` is 0.
1244         ///
1245         /// # Examples
1246         ///
1247         /// Basic usage:
1248         ///
1249         /// ```
1250         #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);")]
1251         /// assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
1252         /// ```
1253         #[stable(feature = "euclidean_division", since = "1.38.0")]
1254         #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1255         #[must_use = "this returns the result of the operation, \
1256                       without modifying the original"]
1257         #[inline]
1258         pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
1259             self.overflowing_div_euclid(rhs).0
1260         }
1261
1262         /// Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1263         /// boundary of the type.
1264         ///
1265         /// Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1266         /// invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1267         /// this function returns `0`.
1268         ///
1269         /// # Panics
1270         ///
1271         /// This function will panic if `rhs` is 0.
1272         ///
1273         /// # Examples
1274         ///
1275         /// Basic usage:
1276         ///
1277         /// ```
1278         #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);")]
1279         /// assert_eq!((-128i8).wrapping_rem(-1), 0);
1280         /// ```
1281         #[stable(feature = "num_wrapping", since = "1.2.0")]
1282         #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1283         #[must_use = "this returns the result of the operation, \
1284                       without modifying the original"]
1285         #[inline]
1286         pub const fn wrapping_rem(self, rhs: Self) -> Self {
1287             self.overflowing_rem(rhs).0
1288         }
1289
1290         /// Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
1291         /// at the boundary of the type.
1292         ///
1293         /// Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1294         /// for the type). In this case, this method returns 0.
1295         ///
1296         /// # Panics
1297         ///
1298         /// This function will panic if `rhs` is 0.
1299         ///
1300         /// # Examples
1301         ///
1302         /// Basic usage:
1303         ///
1304         /// ```
1305         #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);")]
1306         /// assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
1307         /// ```
1308         #[stable(feature = "euclidean_division", since = "1.38.0")]
1309         #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1310         #[must_use = "this returns the result of the operation, \
1311                       without modifying the original"]
1312         #[inline]
1313         pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1314             self.overflowing_rem_euclid(rhs).0
1315         }
1316
1317         /// Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1318         /// of the type.
1319         ///
1320         /// The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1321         /// is the negative minimal value for the type); this is a positive value that is too large to represent
1322         /// in the type. In such a case, this function returns `MIN` itself.
1323         ///
1324         /// # Examples
1325         ///
1326         /// Basic usage:
1327         ///
1328         /// ```
1329         #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);")]
1330         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.wrapping_neg(), ", stringify!($SelfT), "::MIN);")]
1331         /// ```
1332         #[stable(feature = "num_wrapping", since = "1.2.0")]
1333         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1334         #[must_use = "this returns the result of the operation, \
1335                       without modifying the original"]
1336         #[inline(always)]
1337         pub const fn wrapping_neg(self) -> Self {
1338             (0 as $SelfT).wrapping_sub(self)
1339         }
1340
1341         /// Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1342         /// any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1343         ///
1344         /// Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1345         /// the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1346         /// The primitive integer types all implement a [`rotate_left`](Self::rotate_left) function,
1347         /// which may be what you want instead.
1348         ///
1349         /// # Examples
1350         ///
1351         /// Basic usage:
1352         ///
1353         /// ```
1354         #[doc = concat!("assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);")]
1355         #[doc = concat!("assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);")]
1356         /// ```
1357         #[stable(feature = "num_wrapping", since = "1.2.0")]
1358         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1359         #[must_use = "this returns the result of the operation, \
1360                       without modifying the original"]
1361         #[inline(always)]
1362         pub const fn wrapping_shl(self, rhs: u32) -> Self {
1363             // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1364             // out of bounds
1365             unsafe {
1366                 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1367             }
1368         }
1369
1370         /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1371         /// removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1372         ///
1373         /// Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1374         /// to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1375         /// end. The primitive integer types all implement a [`rotate_right`](Self::rotate_right) function,
1376         /// which may be what you want instead.
1377         ///
1378         /// # Examples
1379         ///
1380         /// Basic usage:
1381         ///
1382         /// ```
1383         #[doc = concat!("assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);")]
1384         /// assert_eq!((-128i16).wrapping_shr(64), -128);
1385         /// ```
1386         #[stable(feature = "num_wrapping", since = "1.2.0")]
1387         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1388         #[must_use = "this returns the result of the operation, \
1389                       without modifying the original"]
1390         #[inline(always)]
1391         pub const fn wrapping_shr(self, rhs: u32) -> Self {
1392             // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1393             // out of bounds
1394             unsafe {
1395                 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1396             }
1397         }
1398
1399         /// Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1400         /// the boundary of the type.
1401         ///
1402         /// The only case where such wrapping can occur is when one takes the absolute value of the negative
1403         /// minimal value for the type; this is a positive value that is too large to represent in the type. In
1404         /// such a case, this function returns `MIN` itself.
1405         ///
1406         /// # Examples
1407         ///
1408         /// Basic usage:
1409         ///
1410         /// ```
1411         #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);")]
1412         #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);")]
1413         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.wrapping_abs(), ", stringify!($SelfT), "::MIN);")]
1414         /// assert_eq!((-128i8).wrapping_abs() as u8, 128);
1415         /// ```
1416         #[stable(feature = "no_panic_abs", since = "1.13.0")]
1417         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1418         #[must_use = "this returns the result of the operation, \
1419                       without modifying the original"]
1420         #[allow(unused_attributes)]
1421         #[inline]
1422         pub const fn wrapping_abs(self) -> Self {
1423              if self.is_negative() {
1424                  self.wrapping_neg()
1425              } else {
1426                  self
1427              }
1428         }
1429
1430         /// Computes the absolute value of `self` without any wrapping
1431         /// or panicking.
1432         ///
1433         ///
1434         /// # Examples
1435         ///
1436         /// Basic usage:
1437         ///
1438         /// ```
1439         #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".unsigned_abs(), 100", stringify!($UnsignedT), ");")]
1440         #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").unsigned_abs(), 100", stringify!($UnsignedT), ");")]
1441         /// assert_eq!((-128i8).unsigned_abs(), 128u8);
1442         /// ```
1443         #[stable(feature = "unsigned_abs", since = "1.51.0")]
1444         #[rustc_const_stable(feature = "unsigned_abs", since = "1.51.0")]
1445         #[must_use = "this returns the result of the operation, \
1446                       without modifying the original"]
1447         #[inline]
1448         pub const fn unsigned_abs(self) -> $UnsignedT {
1449              self.wrapping_abs() as $UnsignedT
1450         }
1451
1452         /// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1453         /// wrapping around at the boundary of the type.
1454         ///
1455         /// # Examples
1456         ///
1457         /// Basic usage:
1458         ///
1459         /// ```
1460         #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);")]
1461         /// assert_eq!(3i8.wrapping_pow(5), -13);
1462         /// assert_eq!(3i8.wrapping_pow(6), -39);
1463         /// ```
1464         #[stable(feature = "no_panic_pow", since = "1.34.0")]
1465         #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1466         #[must_use = "this returns the result of the operation, \
1467                       without modifying the original"]
1468         #[inline]
1469         pub const fn wrapping_pow(self, mut exp: u32) -> Self {
1470             if exp == 0 {
1471                 return 1;
1472             }
1473             let mut base = self;
1474             let mut acc: Self = 1;
1475
1476             while exp > 1 {
1477                 if (exp & 1) == 1 {
1478                     acc = acc.wrapping_mul(base);
1479                 }
1480                 exp /= 2;
1481                 base = base.wrapping_mul(base);
1482             }
1483
1484             // since exp!=0, finally the exp must be 1.
1485             // Deal with the final bit of the exponent separately, since
1486             // squaring the base afterwards is not necessary and may cause a
1487             // needless overflow.
1488             acc.wrapping_mul(base)
1489         }
1490
1491         /// Calculates `self` + `rhs`
1492         ///
1493         /// Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1494         /// occur. If an overflow would have occurred then the wrapped value is returned.
1495         ///
1496         /// # Examples
1497         ///
1498         /// Basic usage:
1499         ///
1500         /// ```
1501         ///
1502         #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));")]
1503         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT), "::MIN, true));")]
1504         /// ```
1505         #[stable(feature = "wrapping", since = "1.7.0")]
1506         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1507         #[must_use = "this returns the result of the operation, \
1508                       without modifying the original"]
1509         #[inline(always)]
1510         pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1511             let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1512             (a as Self, b)
1513         }
1514
1515         /// Calculates `self` + `rhs` with an unsigned `rhs`
1516         ///
1517         /// Returns a tuple of the addition along with a boolean indicating
1518         /// whether an arithmetic overflow would occur. If an overflow would
1519         /// have occurred then the wrapped value is returned.
1520         ///
1521         /// # Examples
1522         ///
1523         /// Basic usage:
1524         ///
1525         /// ```
1526         /// # #![feature(mixed_integer_ops)]
1527         #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_unsigned(2), (3, false));")]
1528         #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN).overflowing_add_unsigned(", stringify!($UnsignedT), "::MAX), (", stringify!($SelfT), "::MAX, false));")]
1529         #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).overflowing_add_unsigned(3), (", stringify!($SelfT), "::MIN, true));")]
1530         /// ```
1531         #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1532         #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1533         #[must_use = "this returns the result of the operation, \
1534                       without modifying the original"]
1535         #[inline]
1536         pub const fn overflowing_add_unsigned(self, rhs: $UnsignedT) -> (Self, bool) {
1537             let rhs = rhs as Self;
1538             let (res, overflowed) = self.overflowing_add(rhs);
1539             (res, overflowed ^ (rhs < 0))
1540         }
1541
1542         /// Calculates `self` - `rhs`
1543         ///
1544         /// Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1545         /// would occur. If an overflow would have occurred then the wrapped value is returned.
1546         ///
1547         /// # Examples
1548         ///
1549         /// Basic usage:
1550         ///
1551         /// ```
1552         ///
1553         #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));")]
1554         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")]
1555         /// ```
1556         #[stable(feature = "wrapping", since = "1.7.0")]
1557         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1558         #[must_use = "this returns the result of the operation, \
1559                       without modifying the original"]
1560         #[inline(always)]
1561         pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1562             let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1563             (a as Self, b)
1564         }
1565
1566         /// Calculates `self` - `rhs` with an unsigned `rhs`
1567         ///
1568         /// Returns a tuple of the subtraction along with a boolean indicating
1569         /// whether an arithmetic overflow would occur. If an overflow would
1570         /// have occurred then the wrapped value is returned.
1571         ///
1572         /// # Examples
1573         ///
1574         /// Basic usage:
1575         ///
1576         /// ```
1577         /// # #![feature(mixed_integer_ops)]
1578         #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_sub_unsigned(2), (-1, false));")]
1579         #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX).overflowing_sub_unsigned(", stringify!($UnsignedT), "::MAX), (", stringify!($SelfT), "::MIN, false));")]
1580         #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 2).overflowing_sub_unsigned(3), (", stringify!($SelfT), "::MAX, true));")]
1581         /// ```
1582         #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1583         #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1584         #[must_use = "this returns the result of the operation, \
1585                       without modifying the original"]
1586         #[inline]
1587         pub const fn overflowing_sub_unsigned(self, rhs: $UnsignedT) -> (Self, bool) {
1588             let rhs = rhs as Self;
1589             let (res, overflowed) = self.overflowing_sub(rhs);
1590             (res, overflowed ^ (rhs < 0))
1591         }
1592
1593         /// Calculates the multiplication of `self` and `rhs`.
1594         ///
1595         /// Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1596         /// would occur. If an overflow would have occurred then the wrapped value is returned.
1597         ///
1598         /// # Examples
1599         ///
1600         /// Basic usage:
1601         ///
1602         /// ```
1603         #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));")]
1604         /// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
1605         /// ```
1606         #[stable(feature = "wrapping", since = "1.7.0")]
1607         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1608         #[must_use = "this returns the result of the operation, \
1609                       without modifying the original"]
1610         #[inline(always)]
1611         pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1612             let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1613             (a as Self, b)
1614         }
1615
1616         /// Calculates the divisor when `self` is divided by `rhs`.
1617         ///
1618         /// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1619         /// occur. If an overflow would occur then self is returned.
1620         ///
1621         /// # Panics
1622         ///
1623         /// This function will panic if `rhs` is 0.
1624         ///
1625         /// # Examples
1626         ///
1627         /// Basic usage:
1628         ///
1629         /// ```
1630         ///
1631         #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));")]
1632         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT), "::MIN, true));")]
1633         /// ```
1634         #[inline]
1635         #[stable(feature = "wrapping", since = "1.7.0")]
1636         #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1637         #[must_use = "this returns the result of the operation, \
1638                       without modifying the original"]
1639         pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1640             // Using `&` helps LLVM see that it is the same check made in division.
1641             if unlikely!((self == Self::MIN) & (rhs == -1)) {
1642                 (self, true)
1643             } else {
1644                 (self / rhs, false)
1645             }
1646         }
1647
1648         /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1649         ///
1650         /// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1651         /// occur. If an overflow would occur then `self` is returned.
1652         ///
1653         /// # Panics
1654         ///
1655         /// This function will panic if `rhs` is 0.
1656         ///
1657         /// # Examples
1658         ///
1659         /// Basic usage:
1660         ///
1661         /// ```
1662         #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));")]
1663         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euclid(-1), (", stringify!($SelfT), "::MIN, true));")]
1664         /// ```
1665         #[inline]
1666         #[stable(feature = "euclidean_division", since = "1.38.0")]
1667         #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1668         #[must_use = "this returns the result of the operation, \
1669                       without modifying the original"]
1670         pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1671             // Using `&` helps LLVM see that it is the same check made in division.
1672             if unlikely!((self == Self::MIN) & (rhs == -1)) {
1673                 (self, true)
1674             } else {
1675                 (self.div_euclid(rhs), false)
1676             }
1677         }
1678
1679         /// Calculates the remainder when `self` is divided by `rhs`.
1680         ///
1681         /// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1682         /// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1683         ///
1684         /// # Panics
1685         ///
1686         /// This function will panic if `rhs` is 0.
1687         ///
1688         /// # Examples
1689         ///
1690         /// Basic usage:
1691         ///
1692         /// ```
1693         ///
1694         #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));")]
1695         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));")]
1696         /// ```
1697         #[inline]
1698         #[stable(feature = "wrapping", since = "1.7.0")]
1699         #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1700         #[must_use = "this returns the result of the operation, \
1701                       without modifying the original"]
1702         pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1703             if unlikely!(rhs == -1) {
1704                 (0, self == Self::MIN)
1705             } else {
1706                 (self % rhs, false)
1707             }
1708         }
1709
1710
1711         /// Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
1712         ///
1713         /// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1714         /// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1715         ///
1716         /// # Panics
1717         ///
1718         /// This function will panic if `rhs` is 0.
1719         ///
1720         /// # Examples
1721         ///
1722         /// Basic usage:
1723         ///
1724         /// ```
1725         #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));")]
1726         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem_euclid(-1), (0, true));")]
1727         /// ```
1728         #[stable(feature = "euclidean_division", since = "1.38.0")]
1729         #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1730         #[must_use = "this returns the result of the operation, \
1731                       without modifying the original"]
1732         #[inline]
1733         pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1734             if unlikely!(rhs == -1) {
1735                 (0, self == Self::MIN)
1736             } else {
1737                 (self.rem_euclid(rhs), false)
1738             }
1739         }
1740
1741
1742         /// Negates self, overflowing if this is equal to the minimum value.
1743         ///
1744         /// Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1745         /// happened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the
1746         /// minimum value will be returned again and `true` will be returned for an overflow happening.
1747         ///
1748         /// # Examples
1749         ///
1750         /// Basic usage:
1751         ///
1752         /// ```
1753         #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));")]
1754         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT), "::MIN, true));")]
1755         /// ```
1756         #[inline]
1757         #[stable(feature = "wrapping", since = "1.7.0")]
1758         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1759         #[must_use = "this returns the result of the operation, \
1760                       without modifying the original"]
1761         #[allow(unused_attributes)]
1762         pub const fn overflowing_neg(self) -> (Self, bool) {
1763             if unlikely!(self == Self::MIN) {
1764                 (Self::MIN, true)
1765             } else {
1766                 (-self, false)
1767             }
1768         }
1769
1770         /// Shifts self left by `rhs` bits.
1771         ///
1772         /// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1773         /// value was larger than or equal to the number of bits. If the shift value is too large, then value is
1774         /// masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1775         ///
1776         /// # Examples
1777         ///
1778         /// Basic usage:
1779         ///
1780         /// ```
1781         #[doc = concat!("assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));")]
1782         /// assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));
1783         /// ```
1784         #[stable(feature = "wrapping", since = "1.7.0")]
1785         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1786         #[must_use = "this returns the result of the operation, \
1787                       without modifying the original"]
1788         #[inline]
1789         pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1790             (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1791         }
1792
1793         /// Shifts self right by `rhs` bits.
1794         ///
1795         /// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1796         /// value was larger than or equal to the number of bits. If the shift value is too large, then value is
1797         /// masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1798         ///
1799         /// # Examples
1800         ///
1801         /// Basic usage:
1802         ///
1803         /// ```
1804         #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));")]
1805         /// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
1806         /// ```
1807         #[stable(feature = "wrapping", since = "1.7.0")]
1808         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1809         #[must_use = "this returns the result of the operation, \
1810                       without modifying the original"]
1811         #[inline]
1812         pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1813             (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1814         }
1815
1816         /// Computes the absolute value of `self`.
1817         ///
1818         /// Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1819         /// happened. If self is the minimum value
1820         #[doc = concat!("(e.g., ", stringify!($SelfT), "::MIN for values of type ", stringify!($SelfT), "),")]
1821         /// then the minimum value will be returned again and true will be returned
1822         /// for an overflow happening.
1823         ///
1824         /// # Examples
1825         ///
1826         /// Basic usage:
1827         ///
1828         /// ```
1829         #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));")]
1830         #[doc = concat!("assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));")]
1831         #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN).overflowing_abs(), (", stringify!($SelfT), "::MIN, true));")]
1832         /// ```
1833         #[stable(feature = "no_panic_abs", since = "1.13.0")]
1834         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1835         #[must_use = "this returns the result of the operation, \
1836                       without modifying the original"]
1837         #[inline]
1838         pub const fn overflowing_abs(self) -> (Self, bool) {
1839             (self.wrapping_abs(), self == Self::MIN)
1840         }
1841
1842         /// Raises self to the power of `exp`, using exponentiation by squaring.
1843         ///
1844         /// Returns a tuple of the exponentiation along with a bool indicating
1845         /// whether an overflow happened.
1846         ///
1847         /// # Examples
1848         ///
1849         /// Basic usage:
1850         ///
1851         /// ```
1852         #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));")]
1853         /// assert_eq!(3i8.overflowing_pow(5), (-13, true));
1854         /// ```
1855         #[stable(feature = "no_panic_pow", since = "1.34.0")]
1856         #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1857         #[must_use = "this returns the result of the operation, \
1858                       without modifying the original"]
1859         #[inline]
1860         pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1861             if exp == 0 {
1862                 return (1,false);
1863             }
1864             let mut base = self;
1865             let mut acc: Self = 1;
1866             let mut overflown = false;
1867             // Scratch space for storing results of overflowing_mul.
1868             let mut r;
1869
1870             while exp > 1 {
1871                 if (exp & 1) == 1 {
1872                     r = acc.overflowing_mul(base);
1873                     acc = r.0;
1874                     overflown |= r.1;
1875                 }
1876                 exp /= 2;
1877                 r = base.overflowing_mul(base);
1878                 base = r.0;
1879                 overflown |= r.1;
1880             }
1881
1882             // since exp!=0, finally the exp must be 1.
1883             // Deal with the final bit of the exponent separately, since
1884             // squaring the base afterwards is not necessary and may cause a
1885             // needless overflow.
1886             r = acc.overflowing_mul(base);
1887             r.1 |= overflown;
1888             r
1889         }
1890
1891         /// Raises self to the power of `exp`, using exponentiation by squaring.
1892         ///
1893         /// # Examples
1894         ///
1895         /// Basic usage:
1896         ///
1897         /// ```
1898         #[doc = concat!("let x: ", stringify!($SelfT), " = 2; // or any other integer type")]
1899         ///
1900         /// assert_eq!(x.pow(5), 32);
1901         /// ```
1902         #[stable(feature = "rust1", since = "1.0.0")]
1903         #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1904         #[must_use = "this returns the result of the operation, \
1905                       without modifying the original"]
1906         #[inline]
1907         #[rustc_inherit_overflow_checks]
1908         pub const fn pow(self, mut exp: u32) -> Self {
1909             if exp == 0 {
1910                 return 1;
1911             }
1912             let mut base = self;
1913             let mut acc = 1;
1914
1915             while exp > 1 {
1916                 if (exp & 1) == 1 {
1917                     acc = acc * base;
1918                 }
1919                 exp /= 2;
1920                 base = base * base;
1921             }
1922
1923             // since exp!=0, finally the exp must be 1.
1924             // Deal with the final bit of the exponent separately, since
1925             // squaring the base afterwards is not necessary and may cause a
1926             // needless overflow.
1927             acc * base
1928         }
1929
1930         /// Calculates the quotient of Euclidean division of `self` by `rhs`.
1931         ///
1932         /// This computes the integer `q` such that `self = q * rhs + r`, with
1933         /// `r = self.rem_euclid(rhs)` and `0 <= r < abs(rhs)`.
1934         ///
1935         /// In other words, the result is `self / rhs` rounded to the integer `q`
1936         /// such that `self >= q * rhs`.
1937         /// If `self > 0`, this is equal to round towards zero (the default in Rust);
1938         /// if `self < 0`, this is equal to round towards +/- infinity.
1939         ///
1940         /// # Panics
1941         ///
1942         /// This function will panic if `rhs` is 0 or the division results in overflow.
1943         ///
1944         /// # Examples
1945         ///
1946         /// Basic usage:
1947         ///
1948         /// ```
1949         #[doc = concat!("let a: ", stringify!($SelfT), " = 7; // or any other integer type")]
1950         /// let b = 4;
1951         ///
1952         /// assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
1953         /// assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
1954         /// assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
1955         /// assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
1956         /// ```
1957         #[stable(feature = "euclidean_division", since = "1.38.0")]
1958         #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1959         #[must_use = "this returns the result of the operation, \
1960                       without modifying the original"]
1961         #[inline]
1962         #[rustc_inherit_overflow_checks]
1963         pub const fn div_euclid(self, rhs: Self) -> Self {
1964             let q = self / rhs;
1965             if self % rhs < 0 {
1966                 return if rhs > 0 { q - 1 } else { q + 1 }
1967             }
1968             q
1969         }
1970
1971
1972         /// Calculates the least nonnegative remainder of `self (mod rhs)`.
1973         ///
1974         /// This is done as if by the Euclidean division algorithm -- given
1975         /// `r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) + r`, and
1976         /// `0 <= r < abs(rhs)`.
1977         ///
1978         /// # Panics
1979         ///
1980         /// This function will panic if `rhs` is 0 or the division results in overflow.
1981         ///
1982         /// # Examples
1983         ///
1984         /// Basic usage:
1985         ///
1986         /// ```
1987         #[doc = concat!("let a: ", stringify!($SelfT), " = 7; // or any other integer type")]
1988         /// let b = 4;
1989         ///
1990         /// assert_eq!(a.rem_euclid(b), 3);
1991         /// assert_eq!((-a).rem_euclid(b), 1);
1992         /// assert_eq!(a.rem_euclid(-b), 3);
1993         /// assert_eq!((-a).rem_euclid(-b), 1);
1994         /// ```
1995         #[stable(feature = "euclidean_division", since = "1.38.0")]
1996         #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1997         #[must_use = "this returns the result of the operation, \
1998                       without modifying the original"]
1999         #[inline]
2000         #[rustc_inherit_overflow_checks]
2001         pub const fn rem_euclid(self, rhs: Self) -> Self {
2002             let r = self % rhs;
2003             if r < 0 {
2004                 if rhs < 0 {
2005                     r - rhs
2006                 } else {
2007                     r + rhs
2008                 }
2009             } else {
2010                 r
2011             }
2012         }
2013
2014         /// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
2015         ///
2016         /// # Panics
2017         ///
2018         /// This function will panic if `rhs` is zero.
2019         ///
2020         /// ## Overflow behavior
2021         ///
2022         /// On overflow, this function will panic if overflow checks are enabled (default in debug
2023         /// mode) and wrap if overflow checks are disabled (default in release mode).
2024         ///
2025         /// # Examples
2026         ///
2027         /// Basic usage:
2028         ///
2029         /// ```
2030         /// #![feature(int_roundings)]
2031         #[doc = concat!("let a: ", stringify!($SelfT)," = 8;")]
2032         /// let b = 3;
2033         ///
2034         /// assert_eq!(a.div_floor(b), 2);
2035         /// assert_eq!(a.div_floor(-b), -3);
2036         /// assert_eq!((-a).div_floor(b), -3);
2037         /// assert_eq!((-a).div_floor(-b), 2);
2038         /// ```
2039         #[unstable(feature = "int_roundings", issue = "88581")]
2040         #[must_use = "this returns the result of the operation, \
2041                       without modifying the original"]
2042         #[inline]
2043         #[rustc_inherit_overflow_checks]
2044         pub const fn div_floor(self, rhs: Self) -> Self {
2045             let d = self / rhs;
2046             let r = self % rhs;
2047             if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) {
2048                 d - 1
2049             } else {
2050                 d
2051             }
2052         }
2053
2054         /// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
2055         ///
2056         /// # Panics
2057         ///
2058         /// This function will panic if `rhs` is zero.
2059         ///
2060         /// ## Overflow behavior
2061         ///
2062         /// On overflow, this function will panic if overflow checks are enabled (default in debug
2063         /// mode) and wrap if overflow checks are disabled (default in release mode).
2064         ///
2065         /// # Examples
2066         ///
2067         /// Basic usage:
2068         ///
2069         /// ```
2070         /// #![feature(int_roundings)]
2071         #[doc = concat!("let a: ", stringify!($SelfT)," = 8;")]
2072         /// let b = 3;
2073         ///
2074         /// assert_eq!(a.div_ceil(b), 3);
2075         /// assert_eq!(a.div_ceil(-b), -2);
2076         /// assert_eq!((-a).div_ceil(b), -2);
2077         /// assert_eq!((-a).div_ceil(-b), 3);
2078         /// ```
2079         #[unstable(feature = "int_roundings", issue = "88581")]
2080         #[must_use = "this returns the result of the operation, \
2081                       without modifying the original"]
2082         #[inline]
2083         #[rustc_inherit_overflow_checks]
2084         pub const fn div_ceil(self, rhs: Self) -> Self {
2085             let d = self / rhs;
2086             let r = self % rhs;
2087             if (r > 0 && rhs > 0) || (r < 0 && rhs < 0) {
2088                 d + 1
2089             } else {
2090                 d
2091             }
2092         }
2093
2094         /// If `rhs` is positive, calculates the smallest value greater than or
2095         /// equal to `self` that is a multiple of `rhs`. If `rhs` is negative,
2096         /// calculates the largest value less than or equal to `self` that is a
2097         /// multiple of `rhs`.
2098         ///
2099         /// # Panics
2100         ///
2101         /// This function will panic if `rhs` is zero.
2102         ///
2103         /// ## Overflow behavior
2104         ///
2105         /// On overflow, this function will panic if overflow checks are enabled (default in debug
2106         /// mode) and wrap if overflow checks are disabled (default in release mode).
2107         ///
2108         /// # Examples
2109         ///
2110         /// Basic usage:
2111         ///
2112         /// ```
2113         /// #![feature(int_roundings)]
2114         #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".next_multiple_of(8), 16);")]
2115         #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".next_multiple_of(8), 24);")]
2116         #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".next_multiple_of(-8), 16);")]
2117         #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".next_multiple_of(-8), 16);")]
2118         #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").next_multiple_of(8), -16);")]
2119         #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").next_multiple_of(8), -16);")]
2120         #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").next_multiple_of(-8), -16);")]
2121         #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").next_multiple_of(-8), -24);")]
2122         /// ```
2123         #[unstable(feature = "int_roundings", issue = "88581")]
2124         #[must_use = "this returns the result of the operation, \
2125                       without modifying the original"]
2126         #[inline]
2127         #[rustc_inherit_overflow_checks]
2128         pub const fn next_multiple_of(self, rhs: Self) -> Self {
2129             // This would otherwise fail when calculating `r` when self == T::MIN.
2130             if rhs == -1 {
2131                 return self;
2132             }
2133
2134             let r = self % rhs;
2135             let m = if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) {
2136                 r + rhs
2137             } else {
2138                 r
2139             };
2140
2141             if m == 0 {
2142                 self
2143             } else {
2144                 self + (rhs - m)
2145             }
2146         }
2147
2148         /// If `rhs` is positive, calculates the smallest value greater than or
2149         /// equal to `self` that is a multiple of `rhs`. If `rhs` is negative,
2150         /// calculates the largest value less than or equal to `self` that is a
2151         /// multiple of `rhs`. Returns `None` if `rhs` is zero or the operation
2152         /// would result in overflow.
2153         ///
2154         /// # Examples
2155         ///
2156         /// Basic usage:
2157         ///
2158         /// ```
2159         /// #![feature(int_roundings)]
2160         #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(16));")]
2161         #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(24));")]
2162         #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(-8), Some(16));")]
2163         #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(-8), Some(16));")]
2164         #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").checked_next_multiple_of(8), Some(-16));")]
2165         #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").checked_next_multiple_of(8), Some(-16));")]
2166         #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").checked_next_multiple_of(-8), Some(-16));")]
2167         #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").checked_next_multiple_of(-8), Some(-24));")]
2168         #[doc = concat!("assert_eq!(1_", stringify!($SelfT), ".checked_next_multiple_of(0), None);")]
2169         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_multiple_of(2), None);")]
2170         /// ```
2171         #[unstable(feature = "int_roundings", issue = "88581")]
2172         #[must_use = "this returns the result of the operation, \
2173                       without modifying the original"]
2174         #[inline]
2175         pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
2176             // This would otherwise fail when calculating `r` when self == T::MIN.
2177             if rhs == -1 {
2178                 return Some(self);
2179             }
2180
2181             let r = try_opt!(self.checked_rem(rhs));
2182             let m = if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) {
2183                 // r + rhs cannot overflow because they have opposite signs
2184                 r + rhs
2185             } else {
2186                 r
2187             };
2188
2189             if m == 0 {
2190                 Some(self)
2191             } else {
2192                 // rhs - m cannot overflow because m has the same sign as rhs
2193                 self.checked_add(rhs - m)
2194             }
2195         }
2196
2197         /// Returns the logarithm of the number with respect to an arbitrary base,
2198         /// rounded down.
2199         ///
2200         /// This method might not be optimized owing to implementation details;
2201         /// `log2` can produce results more efficiently for base 2, and `log10`
2202         /// can produce results more efficiently for base 10.
2203         ///
2204         /// # Panics
2205         ///
2206         /// When the number is negative, zero, or if the base is not at least 2; it
2207         /// panics in debug mode and the return value is 0 in release
2208         /// mode.
2209         ///
2210         /// # Examples
2211         ///
2212         /// ```
2213         /// #![feature(int_log)]
2214         #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".log(5), 1);")]
2215         /// ```
2216         #[unstable(feature = "int_log", issue = "70887")]
2217         #[must_use = "this returns the result of the operation, \
2218                       without modifying the original"]
2219         #[inline]
2220         #[track_caller]
2221         #[rustc_inherit_overflow_checks]
2222         #[allow(arithmetic_overflow)]
2223         pub const fn log(self, base: Self) -> u32 {
2224             match self.checked_log(base) {
2225                 Some(n) => n,
2226                 None => {
2227                     // In debug builds, trigger a panic on None.
2228                     // This should optimize completely out in release builds.
2229                     let _ = Self::MAX + 1;
2230
2231                     0
2232                 },
2233             }
2234         }
2235
2236         /// Returns the base 2 logarithm of the number, rounded down.
2237         ///
2238         /// # Panics
2239         ///
2240         /// When the number is negative or zero it panics in debug mode and the return value
2241         /// is 0 in release mode.
2242         ///
2243         /// # Examples
2244         ///
2245         /// ```
2246         /// #![feature(int_log)]
2247         #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".log2(), 1);")]
2248         /// ```
2249         #[unstable(feature = "int_log", issue = "70887")]
2250         #[must_use = "this returns the result of the operation, \
2251                       without modifying the original"]
2252         #[inline]
2253         #[track_caller]
2254         #[rustc_inherit_overflow_checks]
2255         #[allow(arithmetic_overflow)]
2256         pub const fn log2(self) -> u32 {
2257             match self.checked_log2() {
2258                 Some(n) => n,
2259                 None => {
2260                     // In debug builds, trigger a panic on None.
2261                     // This should optimize completely out in release builds.
2262                     let _ = Self::MAX + 1;
2263
2264                     0
2265                 },
2266             }
2267         }
2268
2269         /// Returns the base 10 logarithm of the number, rounded down.
2270         ///
2271         /// # Panics
2272         ///
2273         /// When the number is negative or zero it panics in debug mode and the return value
2274         /// is 0 in release mode.
2275         ///
2276         /// # Example
2277         ///
2278         /// ```
2279         /// #![feature(int_log)]
2280         #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".log10(), 1);")]
2281         /// ```
2282         #[unstable(feature = "int_log", issue = "70887")]
2283         #[must_use = "this returns the result of the operation, \
2284                       without modifying the original"]
2285         #[inline]
2286         #[track_caller]
2287         #[rustc_inherit_overflow_checks]
2288         #[allow(arithmetic_overflow)]
2289         pub const fn log10(self) -> u32 {
2290             match self.checked_log10() {
2291                 Some(n) => n,
2292                 None => {
2293                     // In debug builds, trigger a panic on None.
2294                     // This should optimize completely out in release builds.
2295                     let _ = Self::MAX + 1;
2296
2297                     0
2298                 },
2299             }
2300         }
2301
2302         /// Returns the logarithm of the number with respect to an arbitrary base,
2303         /// rounded down.
2304         ///
2305         /// Returns `None` if the number is negative or zero, or if the base is not at least 2.
2306         ///
2307         /// This method might not be optimized owing to implementation details;
2308         /// `checked_log2` can produce results more efficiently for base 2, and
2309         /// `checked_log10` can produce results more efficiently for base 10.
2310         ///
2311         /// # Examples
2312         ///
2313         /// ```
2314         /// #![feature(int_log)]
2315         #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_log(5), Some(1));")]
2316         /// ```
2317         #[unstable(feature = "int_log", issue = "70887")]
2318         #[must_use = "this returns the result of the operation, \
2319                       without modifying the original"]
2320         #[inline]
2321         pub const fn checked_log(self, base: Self) -> Option<u32> {
2322             if self <= 0 || base <= 1 {
2323                 None
2324             } else {
2325                 let mut n = 0;
2326                 let mut r = self;
2327
2328                 // Optimization for 128 bit wide integers.
2329                 if Self::BITS == 128 {
2330                     let b = Self::log2(self) / (Self::log2(base) + 1);
2331                     n += b;
2332                     r /= base.pow(b as u32);
2333                 }
2334
2335                 while r >= base {
2336                     r /= base;
2337                     n += 1;
2338                 }
2339                 Some(n)
2340             }
2341         }
2342
2343         /// Returns the base 2 logarithm of the number, rounded down.
2344         ///
2345         /// Returns `None` if the number is negative or zero.
2346         ///
2347         /// # Examples
2348         ///
2349         /// ```
2350         /// #![feature(int_log)]
2351         #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_log2(), Some(1));")]
2352         /// ```
2353         #[unstable(feature = "int_log", issue = "70887")]
2354         #[must_use = "this returns the result of the operation, \
2355                       without modifying the original"]
2356         #[inline]
2357         pub const fn checked_log2(self) -> Option<u32> {
2358             if self <= 0 {
2359                 None
2360             } else {
2361                 // SAFETY: We just checked that this number is positive
2362                 let log = (Self::BITS - 1) - unsafe { intrinsics::ctlz_nonzero(self) as u32 };
2363                 Some(log)
2364             }
2365         }
2366
2367         /// Returns the base 10 logarithm of the number, rounded down.
2368         ///
2369         /// Returns `None` if the number is negative or zero.
2370         ///
2371         /// # Example
2372         ///
2373         /// ```
2374         /// #![feature(int_log)]
2375         #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_log10(), Some(1));")]
2376         /// ```
2377         #[unstable(feature = "int_log", issue = "70887")]
2378         #[must_use = "this returns the result of the operation, \
2379                       without modifying the original"]
2380         #[inline]
2381         pub const fn checked_log10(self) -> Option<u32> {
2382             if self > 0 {
2383                 Some(int_log10::$ActualT(self as $ActualT))
2384             } else {
2385                 None
2386             }
2387         }
2388
2389         /// Computes the absolute value of `self`.
2390         ///
2391         /// # Overflow behavior
2392         ///
2393         /// The absolute value of
2394         #[doc = concat!("`", stringify!($SelfT), "::MIN`")]
2395         /// cannot be represented as an
2396         #[doc = concat!("`", stringify!($SelfT), "`,")]
2397         /// and attempting to calculate it will cause an overflow. This means
2398         /// that code in debug mode will trigger a panic on this case and
2399         /// optimized code will return
2400         #[doc = concat!("`", stringify!($SelfT), "::MIN`")]
2401         /// without a panic.
2402         ///
2403         /// # Examples
2404         ///
2405         /// Basic usage:
2406         ///
2407         /// ```
2408         #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".abs(), 10);")]
2409         #[doc = concat!("assert_eq!((-10", stringify!($SelfT), ").abs(), 10);")]
2410         /// ```
2411         #[stable(feature = "rust1", since = "1.0.0")]
2412         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2413         #[allow(unused_attributes)]
2414         #[must_use = "this returns the result of the operation, \
2415                       without modifying the original"]
2416         #[inline]
2417         #[rustc_inherit_overflow_checks]
2418         pub const fn abs(self) -> Self {
2419             // Note that the #[rustc_inherit_overflow_checks] and #[inline]
2420             // above mean that the overflow semantics of the subtraction
2421             // depend on the crate we're being called from.
2422             if self.is_negative() {
2423                 -self
2424             } else {
2425                 self
2426             }
2427         }
2428
2429         /// Computes the absolute difference between `self` and `other`.
2430         ///
2431         /// This function always returns the correct answer without overflow or
2432         /// panics by returning an unsigned integer.
2433         ///
2434         /// # Examples
2435         ///
2436         /// Basic usage:
2437         ///
2438         /// ```
2439         #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(80), 20", stringify!($UnsignedT), ");")]
2440         #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(110), 10", stringify!($UnsignedT), ");")]
2441         #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").abs_diff(80), 180", stringify!($UnsignedT), ");")]
2442         #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").abs_diff(-120), 20", stringify!($UnsignedT), ");")]
2443         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.abs_diff(", stringify!($SelfT), "::MAX), ", stringify!($UnsignedT), "::MAX);")]
2444         /// ```
2445         #[stable(feature = "int_abs_diff", since = "1.60.0")]
2446         #[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
2447         #[must_use = "this returns the result of the operation, \
2448                       without modifying the original"]
2449         #[inline]
2450         pub const fn abs_diff(self, other: Self) -> $UnsignedT {
2451             if self < other {
2452                 // Converting a non-negative x from signed to unsigned by using
2453                 // `x as U` is left unchanged, but a negative x is converted
2454                 // to value x + 2^N. Thus if `s` and `o` are binary variables
2455                 // respectively indicating whether `self` and `other` are
2456                 // negative, we are computing the mathematical value:
2457                 //
2458                 //    (other + o*2^N) - (self + s*2^N)    mod  2^N
2459                 //    other - self + (o-s)*2^N            mod  2^N
2460                 //    other - self                        mod  2^N
2461                 //
2462                 // Finally, taking the mod 2^N of the mathematical value of
2463                 // `other - self` does not change it as it already is
2464                 // in the range [0, 2^N).
2465                 (other as $UnsignedT).wrapping_sub(self as $UnsignedT)
2466             } else {
2467                 (self as $UnsignedT).wrapping_sub(other as $UnsignedT)
2468             }
2469         }
2470
2471         /// Returns a number representing sign of `self`.
2472         ///
2473         ///  - `0` if the number is zero
2474         ///  - `1` if the number is positive
2475         ///  - `-1` if the number is negative
2476         ///
2477         /// # Examples
2478         ///
2479         /// Basic usage:
2480         ///
2481         /// ```
2482         #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".signum(), 1);")]
2483         #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".signum(), 0);")]
2484         #[doc = concat!("assert_eq!((-10", stringify!($SelfT), ").signum(), -1);")]
2485         /// ```
2486         #[stable(feature = "rust1", since = "1.0.0")]
2487         #[rustc_const_stable(feature = "const_int_sign", since = "1.47.0")]
2488         #[must_use = "this returns the result of the operation, \
2489                       without modifying the original"]
2490         #[inline(always)]
2491         pub const fn signum(self) -> Self {
2492             match self {
2493                 n if n > 0 =>  1,
2494                 0          =>  0,
2495                 _          => -1,
2496             }
2497         }
2498
2499         /// Returns `true` if `self` is positive and `false` if the number is zero or
2500         /// negative.
2501         ///
2502         /// # Examples
2503         ///
2504         /// Basic usage:
2505         ///
2506         /// ```
2507         #[doc = concat!("assert!(10", stringify!($SelfT), ".is_positive());")]
2508         #[doc = concat!("assert!(!(-10", stringify!($SelfT), ").is_positive());")]
2509         /// ```
2510         #[must_use]
2511         #[stable(feature = "rust1", since = "1.0.0")]
2512         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2513         #[inline(always)]
2514         pub const fn is_positive(self) -> bool { self > 0 }
2515
2516         /// Returns `true` if `self` is negative and `false` if the number is zero or
2517         /// positive.
2518         ///
2519         /// # Examples
2520         ///
2521         /// Basic usage:
2522         ///
2523         /// ```
2524         #[doc = concat!("assert!((-10", stringify!($SelfT), ").is_negative());")]
2525         #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_negative());")]
2526         /// ```
2527         #[must_use]
2528         #[stable(feature = "rust1", since = "1.0.0")]
2529         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2530         #[inline(always)]
2531         pub const fn is_negative(self) -> bool { self < 0 }
2532
2533         /// Return the memory representation of this integer as a byte array in
2534         /// big-endian (network) byte order.
2535         ///
2536         #[doc = $to_xe_bytes_doc]
2537         ///
2538         /// # Examples
2539         ///
2540         /// ```
2541         #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();")]
2542         #[doc = concat!("assert_eq!(bytes, ", $be_bytes, ");")]
2543         /// ```
2544         #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2545         #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2546         #[must_use = "this returns the result of the operation, \
2547                       without modifying the original"]
2548         #[inline]
2549         pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2550             self.to_be().to_ne_bytes()
2551         }
2552
2553         /// Return the memory representation of this integer as a byte array in
2554         /// little-endian byte order.
2555         ///
2556         #[doc = $to_xe_bytes_doc]
2557         ///
2558         /// # Examples
2559         ///
2560         /// ```
2561         #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();")]
2562         #[doc = concat!("assert_eq!(bytes, ", $le_bytes, ");")]
2563         /// ```
2564         #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2565         #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2566         #[must_use = "this returns the result of the operation, \
2567                       without modifying the original"]
2568         #[inline]
2569         pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2570             self.to_le().to_ne_bytes()
2571         }
2572
2573         /// Return the memory representation of this integer as a byte array in
2574         /// native byte order.
2575         ///
2576         /// As the target platform's native endianness is used, portable code
2577         /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2578         /// instead.
2579         ///
2580         #[doc = $to_xe_bytes_doc]
2581         ///
2582         /// [`to_be_bytes`]: Self::to_be_bytes
2583         /// [`to_le_bytes`]: Self::to_le_bytes
2584         ///
2585         /// # Examples
2586         ///
2587         /// ```
2588         #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();")]
2589         /// assert_eq!(
2590         ///     bytes,
2591         ///     if cfg!(target_endian = "big") {
2592         #[doc = concat!("        ", $be_bytes)]
2593         ///     } else {
2594         #[doc = concat!("        ", $le_bytes)]
2595         ///     }
2596         /// );
2597         /// ```
2598         #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2599         #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2600         // SAFETY: const sound because integers are plain old datatypes so we can always
2601         // transmute them to arrays of bytes
2602         #[must_use = "this returns the result of the operation, \
2603                       without modifying the original"]
2604         #[inline]
2605         pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2606             // SAFETY: integers are plain old datatypes so we can always transmute them to
2607             // arrays of bytes
2608             unsafe { mem::transmute(self) }
2609         }
2610
2611         /// Create an integer value from its representation as a byte array in
2612         /// big endian.
2613         ///
2614         #[doc = $to_xe_bytes_doc]
2615         ///
2616         /// # Examples
2617         ///
2618         /// ```
2619         #[doc = concat!("let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");")]
2620         #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2621         /// ```
2622         ///
2623         /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2624         ///
2625         /// ```
2626         #[doc = concat!("fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2627         #[doc = concat!("    let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2628         ///     *input = rest;
2629         #[doc = concat!("    ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())")]
2630         /// }
2631         /// ```
2632         #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2633         #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2634         #[must_use]
2635         #[inline]
2636         pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2637             Self::from_be(Self::from_ne_bytes(bytes))
2638         }
2639
2640         /// Create an integer value from its representation as a byte array in
2641         /// little endian.
2642         ///
2643         #[doc = $to_xe_bytes_doc]
2644         ///
2645         /// # Examples
2646         ///
2647         /// ```
2648         #[doc = concat!("let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");")]
2649         #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2650         /// ```
2651         ///
2652         /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2653         ///
2654         /// ```
2655         #[doc = concat!("fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2656         #[doc = concat!("    let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2657         ///     *input = rest;
2658         #[doc = concat!("    ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())")]
2659         /// }
2660         /// ```
2661         #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2662         #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2663         #[must_use]
2664         #[inline]
2665         pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2666             Self::from_le(Self::from_ne_bytes(bytes))
2667         }
2668
2669         /// Create an integer value from its memory representation as a byte
2670         /// array in native endianness.
2671         ///
2672         /// As the target platform's native endianness is used, portable code
2673         /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2674         /// appropriate instead.
2675         ///
2676         /// [`from_be_bytes`]: Self::from_be_bytes
2677         /// [`from_le_bytes`]: Self::from_le_bytes
2678         ///
2679         #[doc = $to_xe_bytes_doc]
2680         ///
2681         /// # Examples
2682         ///
2683         /// ```
2684         #[doc = concat!("let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {")]
2685         #[doc = concat!("    ", $be_bytes)]
2686         /// } else {
2687         #[doc = concat!("    ", $le_bytes)]
2688         /// });
2689         #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2690         /// ```
2691         ///
2692         /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2693         ///
2694         /// ```
2695         #[doc = concat!("fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2696         #[doc = concat!("    let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2697         ///     *input = rest;
2698         #[doc = concat!("    ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())")]
2699         /// }
2700         /// ```
2701         #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2702         #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2703         #[must_use]
2704         // SAFETY: const sound because integers are plain old datatypes so we can always
2705         // transmute to them
2706         #[inline]
2707         pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2708             // SAFETY: integers are plain old datatypes so we can always transmute to them
2709             unsafe { mem::transmute(bytes) }
2710         }
2711
2712         /// New code should prefer to use
2713         #[doc = concat!("[`", stringify!($SelfT), "::MIN", "`] instead.")]
2714         ///
2715         /// Returns the smallest value that can be represented by this integer type.
2716         #[stable(feature = "rust1", since = "1.0.0")]
2717         #[inline(always)]
2718         #[rustc_promotable]
2719         #[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
2720         #[rustc_deprecated(since = "TBD", reason = "replaced by the `MIN` associated constant on this type")]
2721         pub const fn min_value() -> Self {
2722             Self::MIN
2723         }
2724
2725         /// New code should prefer to use
2726         #[doc = concat!("[`", stringify!($SelfT), "::MAX", "`] instead.")]
2727         ///
2728         /// Returns the largest value that can be represented by this integer type.
2729         #[stable(feature = "rust1", since = "1.0.0")]
2730         #[inline(always)]
2731         #[rustc_promotable]
2732         #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2733         #[rustc_deprecated(since = "TBD", reason = "replaced by the `MAX` associated constant on this type")]
2734         pub const fn max_value() -> Self {
2735             Self::MAX
2736         }
2737     }
2738 }