]> git.lizzy.rs Git - rust.git/blob - library/core/src/num/int_macros.rs
Rollup merge of #89876 - AlexApps99:const_ops, r=oli-obk
[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!("-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> - 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 = "const_int_methods", 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_methods", 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_methods", 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         #[must_use = "this returns the result of the operation, \
1068                       without modifying the original"]
1069         #[inline]
1070         pub const fn saturating_div(self, rhs: Self) -> Self {
1071             match self.overflowing_div(rhs) {
1072                 (result, false) => result,
1073                 (_result, true) => Self::MAX, // MIN / -1 is the only possible saturating overflow
1074             }
1075         }
1076
1077         /// Saturating integer exponentiation. Computes `self.pow(exp)`,
1078         /// saturating at the numeric bounds instead of overflowing.
1079         ///
1080         /// # Examples
1081         ///
1082         /// Basic usage:
1083         ///
1084         /// ```
1085         ///
1086         #[doc = concat!("assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);")]
1087         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);")]
1088         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);")]
1089         /// ```
1090         #[stable(feature = "no_panic_pow", since = "1.34.0")]
1091         #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1092         #[must_use = "this returns the result of the operation, \
1093                       without modifying the original"]
1094         #[inline]
1095         pub const fn saturating_pow(self, exp: u32) -> Self {
1096             match self.checked_pow(exp) {
1097                 Some(x) => x,
1098                 None if self < 0 && exp % 2 == 1 => Self::MIN,
1099                 None => Self::MAX,
1100             }
1101         }
1102
1103         /// Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
1104         /// boundary of the type.
1105         ///
1106         /// # Examples
1107         ///
1108         /// Basic usage:
1109         ///
1110         /// ```
1111         #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);")]
1112         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_add(2), ", stringify!($SelfT), "::MIN + 1);")]
1113         /// ```
1114         #[stable(feature = "rust1", since = "1.0.0")]
1115         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1116         #[must_use = "this returns the result of the operation, \
1117                       without modifying the original"]
1118         #[inline(always)]
1119         pub const fn wrapping_add(self, rhs: Self) -> Self {
1120             intrinsics::wrapping_add(self, rhs)
1121         }
1122
1123         /// Wrapping (modular) addition with an unsigned integer. Computes
1124         /// `self + rhs`, wrapping around at the boundary of the type.
1125         ///
1126         /// # Examples
1127         ///
1128         /// Basic usage:
1129         ///
1130         /// ```
1131         /// # #![feature(mixed_integer_ops)]
1132         #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_add_unsigned(27), 127);")]
1133         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_add_unsigned(2), ", stringify!($SelfT), "::MIN + 1);")]
1134         /// ```
1135         #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1136         #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1137         #[must_use = "this returns the result of the operation, \
1138                       without modifying the original"]
1139         #[inline(always)]
1140         pub const fn wrapping_add_unsigned(self, rhs: $UnsignedT) -> Self {
1141             self.wrapping_add(rhs as Self)
1142         }
1143
1144         /// Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
1145         /// boundary of the type.
1146         ///
1147         /// # Examples
1148         ///
1149         /// Basic usage:
1150         ///
1151         /// ```
1152         #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);")]
1153         #[doc = concat!("assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::MAX), ", stringify!($SelfT), "::MAX);")]
1154         /// ```
1155         #[stable(feature = "rust1", since = "1.0.0")]
1156         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1157         #[must_use = "this returns the result of the operation, \
1158                       without modifying the original"]
1159         #[inline(always)]
1160         pub const fn wrapping_sub(self, rhs: Self) -> Self {
1161             intrinsics::wrapping_sub(self, rhs)
1162         }
1163
1164         /// Wrapping (modular) subtraction with an unsigned integer. Computes
1165         /// `self - rhs`, wrapping around at the boundary of the type.
1166         ///
1167         /// # Examples
1168         ///
1169         /// Basic usage:
1170         ///
1171         /// ```
1172         /// # #![feature(mixed_integer_ops)]
1173         #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".wrapping_sub_unsigned(127), -127);")]
1174         #[doc = concat!("assert_eq!((-2", stringify!($SelfT), ").wrapping_sub_unsigned(", stringify!($UnsignedT), "::MAX), -1);")]
1175         /// ```
1176         #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1177         #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1178         #[must_use = "this returns the result of the operation, \
1179                       without modifying the original"]
1180         #[inline(always)]
1181         pub const fn wrapping_sub_unsigned(self, rhs: $UnsignedT) -> Self {
1182             self.wrapping_sub(rhs as Self)
1183         }
1184
1185         /// Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1186         /// the boundary of the type.
1187         ///
1188         /// # Examples
1189         ///
1190         /// Basic usage:
1191         ///
1192         /// ```
1193         #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);")]
1194         /// assert_eq!(11i8.wrapping_mul(12), -124);
1195         /// ```
1196         #[stable(feature = "rust1", since = "1.0.0")]
1197         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1198         #[must_use = "this returns the result of the operation, \
1199                       without modifying the original"]
1200         #[inline(always)]
1201         pub const fn wrapping_mul(self, rhs: Self) -> Self {
1202             intrinsics::wrapping_mul(self, rhs)
1203         }
1204
1205         /// Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1206         /// boundary of the type.
1207         ///
1208         /// The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1209         /// `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1210         /// that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1211         ///
1212         /// # Panics
1213         ///
1214         /// This function will panic if `rhs` is 0.
1215         ///
1216         /// # Examples
1217         ///
1218         /// Basic usage:
1219         ///
1220         /// ```
1221         #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);")]
1222         /// assert_eq!((-128i8).wrapping_div(-1), -128);
1223         /// ```
1224         #[stable(feature = "num_wrapping", since = "1.2.0")]
1225         #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1226         #[must_use = "this returns the result of the operation, \
1227                       without modifying the original"]
1228         #[inline]
1229         pub const fn wrapping_div(self, rhs: Self) -> Self {
1230             self.overflowing_div(rhs).0
1231         }
1232
1233         /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
1234         /// wrapping around at the boundary of the type.
1235         ///
1236         /// Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1237         /// for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1238         /// type. In this case, this method returns `MIN` itself.
1239         ///
1240         /// # Panics
1241         ///
1242         /// This function will panic if `rhs` is 0.
1243         ///
1244         /// # Examples
1245         ///
1246         /// Basic usage:
1247         ///
1248         /// ```
1249         #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);")]
1250         /// assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
1251         /// ```
1252         #[stable(feature = "euclidean_division", since = "1.38.0")]
1253         #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1254         #[must_use = "this returns the result of the operation, \
1255                       without modifying the original"]
1256         #[inline]
1257         pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
1258             self.overflowing_div_euclid(rhs).0
1259         }
1260
1261         /// Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1262         /// boundary of the type.
1263         ///
1264         /// Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1265         /// invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1266         /// this function returns `0`.
1267         ///
1268         /// # Panics
1269         ///
1270         /// This function will panic if `rhs` is 0.
1271         ///
1272         /// # Examples
1273         ///
1274         /// Basic usage:
1275         ///
1276         /// ```
1277         #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);")]
1278         /// assert_eq!((-128i8).wrapping_rem(-1), 0);
1279         /// ```
1280         #[stable(feature = "num_wrapping", since = "1.2.0")]
1281         #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
1282         #[must_use = "this returns the result of the operation, \
1283                       without modifying the original"]
1284         #[inline]
1285         pub const fn wrapping_rem(self, rhs: Self) -> Self {
1286             self.overflowing_rem(rhs).0
1287         }
1288
1289         /// Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
1290         /// at the boundary of the type.
1291         ///
1292         /// Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1293         /// for the type). In this case, this method returns 0.
1294         ///
1295         /// # Panics
1296         ///
1297         /// This function will panic if `rhs` is 0.
1298         ///
1299         /// # Examples
1300         ///
1301         /// Basic usage:
1302         ///
1303         /// ```
1304         #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);")]
1305         /// assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
1306         /// ```
1307         #[stable(feature = "euclidean_division", since = "1.38.0")]
1308         #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1309         #[must_use = "this returns the result of the operation, \
1310                       without modifying the original"]
1311         #[inline]
1312         pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1313             self.overflowing_rem_euclid(rhs).0
1314         }
1315
1316         /// Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1317         /// of the type.
1318         ///
1319         /// The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1320         /// is the negative minimal value for the type); this is a positive value that is too large to represent
1321         /// in the type. In such a case, this function returns `MIN` itself.
1322         ///
1323         /// # Examples
1324         ///
1325         /// Basic usage:
1326         ///
1327         /// ```
1328         #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);")]
1329         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.wrapping_neg(), ", stringify!($SelfT), "::MIN);")]
1330         /// ```
1331         #[stable(feature = "num_wrapping", since = "1.2.0")]
1332         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1333         #[must_use = "this returns the result of the operation, \
1334                       without modifying the original"]
1335         #[inline(always)]
1336         pub const fn wrapping_neg(self) -> Self {
1337             (0 as $SelfT).wrapping_sub(self)
1338         }
1339
1340         /// Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1341         /// any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1342         ///
1343         /// Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1344         /// the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1345         /// The primitive integer types all implement a [`rotate_left`](Self::rotate_left) function,
1346         /// which may be what you want instead.
1347         ///
1348         /// # Examples
1349         ///
1350         /// Basic usage:
1351         ///
1352         /// ```
1353         #[doc = concat!("assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);")]
1354         #[doc = concat!("assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);")]
1355         /// ```
1356         #[stable(feature = "num_wrapping", since = "1.2.0")]
1357         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1358         #[must_use = "this returns the result of the operation, \
1359                       without modifying the original"]
1360         #[inline(always)]
1361         pub const fn wrapping_shl(self, rhs: u32) -> Self {
1362             // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1363             // out of bounds
1364             unsafe {
1365                 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1366             }
1367         }
1368
1369         /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1370         /// removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1371         ///
1372         /// Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1373         /// to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1374         /// end. The primitive integer types all implement a [`rotate_right`](Self::rotate_right) function,
1375         /// which may be what you want instead.
1376         ///
1377         /// # Examples
1378         ///
1379         /// Basic usage:
1380         ///
1381         /// ```
1382         #[doc = concat!("assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);")]
1383         /// assert_eq!((-128i16).wrapping_shr(64), -128);
1384         /// ```
1385         #[stable(feature = "num_wrapping", since = "1.2.0")]
1386         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1387         #[must_use = "this returns the result of the operation, \
1388                       without modifying the original"]
1389         #[inline(always)]
1390         pub const fn wrapping_shr(self, rhs: u32) -> Self {
1391             // SAFETY: the masking by the bitsize of the type ensures that we do not shift
1392             // out of bounds
1393             unsafe {
1394                 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1395             }
1396         }
1397
1398         /// Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1399         /// the boundary of the type.
1400         ///
1401         /// The only case where such wrapping can occur is when one takes the absolute value of the negative
1402         /// minimal value for the type; this is a positive value that is too large to represent in the type. In
1403         /// such a case, this function returns `MIN` itself.
1404         ///
1405         /// # Examples
1406         ///
1407         /// Basic usage:
1408         ///
1409         /// ```
1410         #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);")]
1411         #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);")]
1412         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.wrapping_abs(), ", stringify!($SelfT), "::MIN);")]
1413         /// assert_eq!((-128i8).wrapping_abs() as u8, 128);
1414         /// ```
1415         #[stable(feature = "no_panic_abs", since = "1.13.0")]
1416         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1417         #[must_use = "this returns the result of the operation, \
1418                       without modifying the original"]
1419         #[allow(unused_attributes)]
1420         #[inline]
1421         pub const fn wrapping_abs(self) -> Self {
1422              if self.is_negative() {
1423                  self.wrapping_neg()
1424              } else {
1425                  self
1426              }
1427         }
1428
1429         /// Computes the absolute value of `self` without any wrapping
1430         /// or panicking.
1431         ///
1432         ///
1433         /// # Examples
1434         ///
1435         /// Basic usage:
1436         ///
1437         /// ```
1438         #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".unsigned_abs(), 100", stringify!($UnsignedT), ");")]
1439         #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").unsigned_abs(), 100", stringify!($UnsignedT), ");")]
1440         /// assert_eq!((-128i8).unsigned_abs(), 128u8);
1441         /// ```
1442         #[stable(feature = "unsigned_abs", since = "1.51.0")]
1443         #[rustc_const_stable(feature = "unsigned_abs", since = "1.51.0")]
1444         #[must_use = "this returns the result of the operation, \
1445                       without modifying the original"]
1446         #[inline]
1447         pub const fn unsigned_abs(self) -> $UnsignedT {
1448              self.wrapping_abs() as $UnsignedT
1449         }
1450
1451         /// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1452         /// wrapping around at the boundary of the type.
1453         ///
1454         /// # Examples
1455         ///
1456         /// Basic usage:
1457         ///
1458         /// ```
1459         #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);")]
1460         /// assert_eq!(3i8.wrapping_pow(5), -13);
1461         /// assert_eq!(3i8.wrapping_pow(6), -39);
1462         /// ```
1463         #[stable(feature = "no_panic_pow", since = "1.34.0")]
1464         #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1465         #[must_use = "this returns the result of the operation, \
1466                       without modifying the original"]
1467         #[inline]
1468         pub const fn wrapping_pow(self, mut exp: u32) -> Self {
1469             if exp == 0 {
1470                 return 1;
1471             }
1472             let mut base = self;
1473             let mut acc: Self = 1;
1474
1475             while exp > 1 {
1476                 if (exp & 1) == 1 {
1477                     acc = acc.wrapping_mul(base);
1478                 }
1479                 exp /= 2;
1480                 base = base.wrapping_mul(base);
1481             }
1482
1483             // since exp!=0, finally the exp must be 1.
1484             // Deal with the final bit of the exponent separately, since
1485             // squaring the base afterwards is not necessary and may cause a
1486             // needless overflow.
1487             acc.wrapping_mul(base)
1488         }
1489
1490         /// Calculates `self` + `rhs`
1491         ///
1492         /// Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1493         /// occur. If an overflow would have occurred then the wrapped value is returned.
1494         ///
1495         /// # Examples
1496         ///
1497         /// Basic usage:
1498         ///
1499         /// ```
1500         ///
1501         #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));")]
1502         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT), "::MIN, true));")]
1503         /// ```
1504         #[stable(feature = "wrapping", since = "1.7.0")]
1505         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1506         #[must_use = "this returns the result of the operation, \
1507                       without modifying the original"]
1508         #[inline(always)]
1509         pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1510             let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
1511             (a as Self, b)
1512         }
1513
1514         /// Calculates `self + rhs + carry` without the ability to overflow.
1515         ///
1516         /// Performs "ternary addition" which takes in an extra bit to add, and may return an
1517         /// additional bit of overflow. This allows for chaining together multiple additions
1518         /// to create "big integers" which represent larger values.
1519         ///
1520         /// # Examples
1521         ///
1522         /// Basic usage
1523         ///
1524         /// ```
1525         /// #![feature(bigint_helper_methods)]
1526         #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".carrying_add(2, false), (7, false));")]
1527         #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".carrying_add(2, true), (8, false));")]
1528         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.carrying_add(1, false), (", stringify!($SelfT), "::MIN, false));")]
1529         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.carrying_add(1, true), (", stringify!($SelfT), "::MIN + 1, false));")]
1530         /// ```
1531         #[unstable(feature = "bigint_helper_methods", issue = "85532")]
1532         #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")]
1533         #[must_use = "this returns the result of the operation, \
1534                       without modifying the original"]
1535         #[inline]
1536         pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
1537             let (sum, carry) = (self as $UnsignedT).carrying_add(rhs as $UnsignedT, carry);
1538             (sum as $SelfT, carry)
1539         }
1540
1541         /// Calculates `self` + `rhs` with an unsigned `rhs`
1542         ///
1543         /// Returns a tuple of the addition along with a boolean indicating
1544         /// whether an arithmetic overflow would occur. If an overflow would
1545         /// have occurred then the wrapped value is returned.
1546         ///
1547         /// # Examples
1548         ///
1549         /// Basic usage:
1550         ///
1551         /// ```
1552         /// # #![feature(mixed_integer_ops)]
1553         #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_unsigned(2), (3, false));")]
1554         #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN).overflowing_add_unsigned(", stringify!($UnsignedT), "::MAX), (", stringify!($SelfT), "::MAX, false));")]
1555         #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).overflowing_add_unsigned(3), (", stringify!($SelfT), "::MIN, true));")]
1556         /// ```
1557         #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1558         #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1559         #[must_use = "this returns the result of the operation, \
1560                       without modifying the original"]
1561         #[inline]
1562         pub const fn overflowing_add_unsigned(self, rhs: $UnsignedT) -> (Self, bool) {
1563             let rhs = rhs as Self;
1564             let (res, overflowed) = self.overflowing_add(rhs);
1565             (res, overflowed ^ (rhs < 0))
1566         }
1567
1568         /// Calculates `self` - `rhs`
1569         ///
1570         /// Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1571         /// would occur. If an overflow would have occurred then the wrapped value is returned.
1572         ///
1573         /// # Examples
1574         ///
1575         /// Basic usage:
1576         ///
1577         /// ```
1578         ///
1579         #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));")]
1580         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")]
1581         /// ```
1582         #[stable(feature = "wrapping", since = "1.7.0")]
1583         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1584         #[must_use = "this returns the result of the operation, \
1585                       without modifying the original"]
1586         #[inline(always)]
1587         pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1588             let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
1589             (a as Self, b)
1590         }
1591
1592         /// Calculates `self - rhs - borrow` without the ability to overflow.
1593         ///
1594         /// Performs "ternary subtraction" which takes in an extra bit to subtract, and may return
1595         /// an additional bit of overflow. This allows for chaining together multiple subtractions
1596         /// to create "big integers" which represent larger values.
1597         ///
1598         /// # Examples
1599         ///
1600         /// Basic usage
1601         ///
1602         /// ```
1603         /// #![feature(bigint_helper_methods)]
1604         #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".borrowing_sub(2, false), (3, false));")]
1605         #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".borrowing_sub(2, true), (2, false));")]
1606         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.borrowing_sub(1, false), (", stringify!($SelfT), "::MAX, false));")]
1607         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.borrowing_sub(1, true), (", stringify!($SelfT), "::MAX - 1, false));")]
1608         /// ```
1609         #[unstable(feature = "bigint_helper_methods", issue = "85532")]
1610         #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")]
1611         #[must_use = "this returns the result of the operation, \
1612                       without modifying the original"]
1613         #[inline]
1614         pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
1615             let (sum, borrow) = (self as $UnsignedT).borrowing_sub(rhs as $UnsignedT, borrow);
1616             (sum as $SelfT, borrow)
1617         }
1618
1619         /// Calculates `self` - `rhs` with an unsigned `rhs`
1620         ///
1621         /// Returns a tuple of the subtraction along with a boolean indicating
1622         /// whether an arithmetic overflow would occur. If an overflow would
1623         /// have occurred then the wrapped value is returned.
1624         ///
1625         /// # Examples
1626         ///
1627         /// Basic usage:
1628         ///
1629         /// ```
1630         /// # #![feature(mixed_integer_ops)]
1631         #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_sub_unsigned(2), (-1, false));")]
1632         #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX).overflowing_sub_unsigned(", stringify!($UnsignedT), "::MAX), (", stringify!($SelfT), "::MIN, false));")]
1633         #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN + 2).overflowing_sub_unsigned(3), (", stringify!($SelfT), "::MAX, true));")]
1634         /// ```
1635         #[unstable(feature = "mixed_integer_ops", issue = "87840")]
1636         #[rustc_const_unstable(feature = "mixed_integer_ops", issue = "87840")]
1637         #[must_use = "this returns the result of the operation, \
1638                       without modifying the original"]
1639         #[inline]
1640         pub const fn overflowing_sub_unsigned(self, rhs: $UnsignedT) -> (Self, bool) {
1641             let rhs = rhs as Self;
1642             let (res, overflowed) = self.overflowing_sub(rhs);
1643             (res, overflowed ^ (rhs < 0))
1644         }
1645
1646         /// Calculates the multiplication of `self` and `rhs`.
1647         ///
1648         /// Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1649         /// would occur. If an overflow would have occurred then the wrapped value is returned.
1650         ///
1651         /// # Examples
1652         ///
1653         /// Basic usage:
1654         ///
1655         /// ```
1656         #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));")]
1657         /// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
1658         /// ```
1659         #[stable(feature = "wrapping", since = "1.7.0")]
1660         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1661         #[must_use = "this returns the result of the operation, \
1662                       without modifying the original"]
1663         #[inline(always)]
1664         pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1665             let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
1666             (a as Self, b)
1667         }
1668
1669         /// Calculates the divisor when `self` is divided by `rhs`.
1670         ///
1671         /// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1672         /// occur. If an overflow would occur then self is returned.
1673         ///
1674         /// # Panics
1675         ///
1676         /// This function will panic if `rhs` is 0.
1677         ///
1678         /// # Examples
1679         ///
1680         /// Basic usage:
1681         ///
1682         /// ```
1683         ///
1684         #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));")]
1685         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT), "::MIN, true));")]
1686         /// ```
1687         #[inline]
1688         #[stable(feature = "wrapping", since = "1.7.0")]
1689         #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1690         #[must_use = "this returns the result of the operation, \
1691                       without modifying the original"]
1692         pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1693             // Using `&` helps LLVM see that it is the same check made in division.
1694             if unlikely!((self == Self::MIN) & (rhs == -1)) {
1695                 (self, true)
1696             } else {
1697                 (self / rhs, false)
1698             }
1699         }
1700
1701         /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1702         ///
1703         /// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1704         /// occur. If an overflow would occur then `self` is returned.
1705         ///
1706         /// # Panics
1707         ///
1708         /// This function will panic if `rhs` is 0.
1709         ///
1710         /// # Examples
1711         ///
1712         /// Basic usage:
1713         ///
1714         /// ```
1715         #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));")]
1716         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euclid(-1), (", stringify!($SelfT), "::MIN, true));")]
1717         /// ```
1718         #[inline]
1719         #[stable(feature = "euclidean_division", since = "1.38.0")]
1720         #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1721         #[must_use = "this returns the result of the operation, \
1722                       without modifying the original"]
1723         pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1724             // Using `&` helps LLVM see that it is the same check made in division.
1725             if unlikely!((self == Self::MIN) & (rhs == -1)) {
1726                 (self, true)
1727             } else {
1728                 (self.div_euclid(rhs), false)
1729             }
1730         }
1731
1732         /// Calculates the remainder when `self` is divided by `rhs`.
1733         ///
1734         /// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1735         /// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1736         ///
1737         /// # Panics
1738         ///
1739         /// This function will panic if `rhs` is 0.
1740         ///
1741         /// # Examples
1742         ///
1743         /// Basic usage:
1744         ///
1745         /// ```
1746         ///
1747         #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));")]
1748         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));")]
1749         /// ```
1750         #[inline]
1751         #[stable(feature = "wrapping", since = "1.7.0")]
1752         #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
1753         #[must_use = "this returns the result of the operation, \
1754                       without modifying the original"]
1755         pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1756             if unlikely!(rhs == -1) {
1757                 (0, self == Self::MIN)
1758             } else {
1759                 (self % rhs, false)
1760             }
1761         }
1762
1763
1764         /// Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
1765         ///
1766         /// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1767         /// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1768         ///
1769         /// # Panics
1770         ///
1771         /// This function will panic if `rhs` is 0.
1772         ///
1773         /// # Examples
1774         ///
1775         /// Basic usage:
1776         ///
1777         /// ```
1778         #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));")]
1779         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem_euclid(-1), (0, true));")]
1780         /// ```
1781         #[stable(feature = "euclidean_division", since = "1.38.0")]
1782         #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1783         #[must_use = "this returns the result of the operation, \
1784                       without modifying the original"]
1785         #[inline]
1786         pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1787             if unlikely!(rhs == -1) {
1788                 (0, self == Self::MIN)
1789             } else {
1790                 (self.rem_euclid(rhs), false)
1791             }
1792         }
1793
1794
1795         /// Negates self, overflowing if this is equal to the minimum value.
1796         ///
1797         /// Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1798         /// happened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the
1799         /// minimum value will be returned again and `true` will be returned for an overflow happening.
1800         ///
1801         /// # Examples
1802         ///
1803         /// Basic usage:
1804         ///
1805         /// ```
1806         #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));")]
1807         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT), "::MIN, true));")]
1808         /// ```
1809         #[inline]
1810         #[stable(feature = "wrapping", since = "1.7.0")]
1811         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1812         #[must_use = "this returns the result of the operation, \
1813                       without modifying the original"]
1814         #[allow(unused_attributes)]
1815         pub const fn overflowing_neg(self) -> (Self, bool) {
1816             if unlikely!(self == Self::MIN) {
1817                 (Self::MIN, true)
1818             } else {
1819                 (-self, false)
1820             }
1821         }
1822
1823         /// Shifts self left by `rhs` bits.
1824         ///
1825         /// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1826         /// value was larger than or equal to the number of bits. If the shift value is too large, then value is
1827         /// masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1828         ///
1829         /// # Examples
1830         ///
1831         /// Basic usage:
1832         ///
1833         /// ```
1834         #[doc = concat!("assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));")]
1835         /// assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));
1836         /// ```
1837         #[stable(feature = "wrapping", since = "1.7.0")]
1838         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1839         #[must_use = "this returns the result of the operation, \
1840                       without modifying the original"]
1841         #[inline]
1842         pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1843             (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1844         }
1845
1846         /// Shifts self right by `rhs` bits.
1847         ///
1848         /// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1849         /// value was larger than or equal to the number of bits. If the shift value is too large, then value is
1850         /// masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1851         ///
1852         /// # Examples
1853         ///
1854         /// Basic usage:
1855         ///
1856         /// ```
1857         #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));")]
1858         /// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
1859         /// ```
1860         #[stable(feature = "wrapping", since = "1.7.0")]
1861         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1862         #[must_use = "this returns the result of the operation, \
1863                       without modifying the original"]
1864         #[inline]
1865         pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1866             (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1867         }
1868
1869         /// Computes the absolute value of `self`.
1870         ///
1871         /// Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1872         /// happened. If self is the minimum value
1873         #[doc = concat!("(e.g., ", stringify!($SelfT), "::MIN for values of type ", stringify!($SelfT), "),")]
1874         /// then the minimum value will be returned again and true will be returned
1875         /// for an overflow happening.
1876         ///
1877         /// # Examples
1878         ///
1879         /// Basic usage:
1880         ///
1881         /// ```
1882         #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));")]
1883         #[doc = concat!("assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));")]
1884         #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MIN).overflowing_abs(), (", stringify!($SelfT), "::MIN, true));")]
1885         /// ```
1886         #[stable(feature = "no_panic_abs", since = "1.13.0")]
1887         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
1888         #[must_use = "this returns the result of the operation, \
1889                       without modifying the original"]
1890         #[inline]
1891         pub const fn overflowing_abs(self) -> (Self, bool) {
1892             (self.wrapping_abs(), self == Self::MIN)
1893         }
1894
1895         /// Raises self to the power of `exp`, using exponentiation by squaring.
1896         ///
1897         /// Returns a tuple of the exponentiation along with a bool indicating
1898         /// whether an overflow happened.
1899         ///
1900         /// # Examples
1901         ///
1902         /// Basic usage:
1903         ///
1904         /// ```
1905         #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));")]
1906         /// assert_eq!(3i8.overflowing_pow(5), (-13, true));
1907         /// ```
1908         #[stable(feature = "no_panic_pow", since = "1.34.0")]
1909         #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1910         #[must_use = "this returns the result of the operation, \
1911                       without modifying the original"]
1912         #[inline]
1913         pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1914             if exp == 0 {
1915                 return (1,false);
1916             }
1917             let mut base = self;
1918             let mut acc: Self = 1;
1919             let mut overflown = false;
1920             // Scratch space for storing results of overflowing_mul.
1921             let mut r;
1922
1923             while exp > 1 {
1924                 if (exp & 1) == 1 {
1925                     r = acc.overflowing_mul(base);
1926                     acc = r.0;
1927                     overflown |= r.1;
1928                 }
1929                 exp /= 2;
1930                 r = base.overflowing_mul(base);
1931                 base = r.0;
1932                 overflown |= r.1;
1933             }
1934
1935             // since exp!=0, finally the exp must be 1.
1936             // Deal with the final bit of the exponent separately, since
1937             // squaring the base afterwards is not necessary and may cause a
1938             // needless overflow.
1939             r = acc.overflowing_mul(base);
1940             r.1 |= overflown;
1941             r
1942         }
1943
1944         /// Raises self to the power of `exp`, using exponentiation by squaring.
1945         ///
1946         /// # Examples
1947         ///
1948         /// Basic usage:
1949         ///
1950         /// ```
1951         #[doc = concat!("let x: ", stringify!($SelfT), " = 2; // or any other integer type")]
1952         ///
1953         /// assert_eq!(x.pow(5), 32);
1954         /// ```
1955         #[stable(feature = "rust1", since = "1.0.0")]
1956         #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1957         #[must_use = "this returns the result of the operation, \
1958                       without modifying the original"]
1959         #[inline]
1960         #[rustc_inherit_overflow_checks]
1961         pub const fn pow(self, mut exp: u32) -> Self {
1962             if exp == 0 {
1963                 return 1;
1964             }
1965             let mut base = self;
1966             let mut acc = 1;
1967
1968             while exp > 1 {
1969                 if (exp & 1) == 1 {
1970                     acc = acc * base;
1971                 }
1972                 exp /= 2;
1973                 base = base * base;
1974             }
1975
1976             // since exp!=0, finally the exp must be 1.
1977             // Deal with the final bit of the exponent separately, since
1978             // squaring the base afterwards is not necessary and may cause a
1979             // needless overflow.
1980             acc * base
1981         }
1982
1983         /// Calculates the quotient of Euclidean division of `self` by `rhs`.
1984         ///
1985         /// This computes the integer `q` such that `self = q * rhs + r`, with
1986         /// `r = self.rem_euclid(rhs)` and `0 <= r < abs(rhs)`.
1987         ///
1988         /// In other words, the result is `self / rhs` rounded to the integer `q`
1989         /// such that `self >= q * rhs`.
1990         /// If `self > 0`, this is equal to round towards zero (the default in Rust);
1991         /// if `self < 0`, this is equal to round towards +/- infinity.
1992         ///
1993         /// # Panics
1994         ///
1995         /// This function will panic if `rhs` is 0 or the division results in overflow.
1996         ///
1997         /// # Examples
1998         ///
1999         /// Basic usage:
2000         ///
2001         /// ```
2002         #[doc = concat!("let a: ", stringify!($SelfT), " = 7; // or any other integer type")]
2003         /// let b = 4;
2004         ///
2005         /// assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
2006         /// assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
2007         /// assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
2008         /// assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
2009         /// ```
2010         #[stable(feature = "euclidean_division", since = "1.38.0")]
2011         #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
2012         #[must_use = "this returns the result of the operation, \
2013                       without modifying the original"]
2014         #[inline]
2015         #[rustc_inherit_overflow_checks]
2016         pub const fn div_euclid(self, rhs: Self) -> Self {
2017             let q = self / rhs;
2018             if self % rhs < 0 {
2019                 return if rhs > 0 { q - 1 } else { q + 1 }
2020             }
2021             q
2022         }
2023
2024
2025         /// Calculates the least nonnegative remainder of `self (mod rhs)`.
2026         ///
2027         /// This is done as if by the Euclidean division algorithm -- given
2028         /// `r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) + r`, and
2029         /// `0 <= r < abs(rhs)`.
2030         ///
2031         /// # Panics
2032         ///
2033         /// This function will panic if `rhs` is 0 or the division results in overflow.
2034         ///
2035         /// # Examples
2036         ///
2037         /// Basic usage:
2038         ///
2039         /// ```
2040         #[doc = concat!("let a: ", stringify!($SelfT), " = 7; // or any other integer type")]
2041         /// let b = 4;
2042         ///
2043         /// assert_eq!(a.rem_euclid(b), 3);
2044         /// assert_eq!((-a).rem_euclid(b), 1);
2045         /// assert_eq!(a.rem_euclid(-b), 3);
2046         /// assert_eq!((-a).rem_euclid(-b), 1);
2047         /// ```
2048         #[stable(feature = "euclidean_division", since = "1.38.0")]
2049         #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
2050         #[must_use = "this returns the result of the operation, \
2051                       without modifying the original"]
2052         #[inline]
2053         #[rustc_inherit_overflow_checks]
2054         pub const fn rem_euclid(self, rhs: Self) -> Self {
2055             let r = self % rhs;
2056             if r < 0 {
2057                 if rhs < 0 {
2058                     r - rhs
2059                 } else {
2060                     r + rhs
2061                 }
2062             } else {
2063                 r
2064             }
2065         }
2066
2067         /// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
2068         ///
2069         /// # Panics
2070         ///
2071         /// This function will panic if `rhs` is 0 or the division results in overflow.
2072         ///
2073         /// # Examples
2074         ///
2075         /// Basic usage:
2076         ///
2077         /// ```
2078         /// #![feature(int_roundings)]
2079         #[doc = concat!("let a: ", stringify!($SelfT)," = 8;")]
2080         /// let b = 3;
2081         ///
2082         /// assert_eq!(a.unstable_div_floor(b), 2);
2083         /// assert_eq!(a.unstable_div_floor(-b), -3);
2084         /// assert_eq!((-a).unstable_div_floor(b), -3);
2085         /// assert_eq!((-a).unstable_div_floor(-b), 2);
2086         /// ```
2087         #[unstable(feature = "int_roundings", issue = "88581")]
2088         #[must_use = "this returns the result of the operation, \
2089                       without modifying the original"]
2090         #[inline]
2091         #[rustc_inherit_overflow_checks]
2092         pub const fn unstable_div_floor(self, rhs: Self) -> Self {
2093             let d = self / rhs;
2094             let r = self % rhs;
2095             if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) {
2096                 d - 1
2097             } else {
2098                 d
2099             }
2100         }
2101
2102         /// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
2103         ///
2104         /// # Panics
2105         ///
2106         /// This function will panic if `rhs` is 0 or the division results in overflow.
2107         ///
2108         /// # Examples
2109         ///
2110         /// Basic usage:
2111         ///
2112         /// ```
2113         /// #![feature(int_roundings)]
2114         #[doc = concat!("let a: ", stringify!($SelfT)," = 8;")]
2115         /// let b = 3;
2116         ///
2117         /// assert_eq!(a.unstable_div_ceil(b), 3);
2118         /// assert_eq!(a.unstable_div_ceil(-b), -2);
2119         /// assert_eq!((-a).unstable_div_ceil(b), -2);
2120         /// assert_eq!((-a).unstable_div_ceil(-b), 3);
2121         /// ```
2122         #[unstable(feature = "int_roundings", issue = "88581")]
2123         #[must_use = "this returns the result of the operation, \
2124                       without modifying the original"]
2125         #[inline]
2126         #[rustc_inherit_overflow_checks]
2127         pub const fn unstable_div_ceil(self, rhs: Self) -> Self {
2128             let d = self / rhs;
2129             let r = self % rhs;
2130             if (r > 0 && rhs > 0) || (r < 0 && rhs < 0) {
2131                 d + 1
2132             } else {
2133                 d
2134             }
2135         }
2136
2137         /// If `rhs` is positive, calculates the smallest value greater than or
2138         /// equal to `self` that is a multiple of `rhs`. If `rhs` is negative,
2139         /// calculates the largest value less than or equal to `self` that is a
2140         /// multiple of `rhs`.
2141         ///
2142         /// # Panics
2143         ///
2144         /// This function will panic if `rhs` is 0 or the operation results in overflow.
2145         ///
2146         /// # Examples
2147         ///
2148         /// Basic usage:
2149         ///
2150         /// ```
2151         /// #![feature(int_roundings)]
2152         #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".unstable_next_multiple_of(8), 16);")]
2153         #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".unstable_next_multiple_of(8), 24);")]
2154         #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".unstable_next_multiple_of(-8), 16);")]
2155         #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".unstable_next_multiple_of(-8), 16);")]
2156         #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").unstable_next_multiple_of(8), -16);")]
2157         #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").unstable_next_multiple_of(8), -16);")]
2158         #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").unstable_next_multiple_of(-8), -16);")]
2159         #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").unstable_next_multiple_of(-8), -24);")]
2160         /// ```
2161         #[unstable(feature = "int_roundings", issue = "88581")]
2162         #[must_use = "this returns the result of the operation, \
2163                       without modifying the original"]
2164         #[inline]
2165         #[rustc_inherit_overflow_checks]
2166         pub const fn unstable_next_multiple_of(self, rhs: Self) -> Self {
2167             // This would otherwise fail when calculating `r` when self == T::MIN.
2168             if rhs == -1 {
2169                 return self;
2170             }
2171
2172             let r = self % rhs;
2173             let m = if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) {
2174                 r + rhs
2175             } else {
2176                 r
2177             };
2178
2179             if m == 0 {
2180                 self
2181             } else {
2182                 self + (rhs - m)
2183             }
2184         }
2185
2186         /// If `rhs` is positive, calculates the smallest value greater than or
2187         /// equal to `self` that is a multiple of `rhs`. If `rhs` is negative,
2188         /// calculates the largest value less than or equal to `self` that is a
2189         /// multiple of `rhs`. Returns `None` if `rhs` is zero or the operation
2190         /// would result in overflow.
2191         ///
2192         /// # Examples
2193         ///
2194         /// Basic usage:
2195         ///
2196         /// ```
2197         /// #![feature(int_roundings)]
2198         #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(16));")]
2199         #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(24));")]
2200         #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(-8), Some(16));")]
2201         #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(-8), Some(16));")]
2202         #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").checked_next_multiple_of(8), Some(-16));")]
2203         #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").checked_next_multiple_of(8), Some(-16));")]
2204         #[doc = concat!("assert_eq!((-16_", stringify!($SelfT), ").checked_next_multiple_of(-8), Some(-16));")]
2205         #[doc = concat!("assert_eq!((-23_", stringify!($SelfT), ").checked_next_multiple_of(-8), Some(-24));")]
2206         #[doc = concat!("assert_eq!(1_", stringify!($SelfT), ".checked_next_multiple_of(0), None);")]
2207         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_multiple_of(2), None);")]
2208         /// ```
2209         #[unstable(feature = "int_roundings", issue = "88581")]
2210         #[must_use = "this returns the result of the operation, \
2211                       without modifying the original"]
2212         #[inline]
2213         #[rustc_inherit_overflow_checks]
2214         pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
2215             // This would otherwise fail when calculating `r` when self == T::MIN.
2216             if rhs == -1 {
2217                 return Some(self);
2218             }
2219
2220             let r = try_opt!(self.checked_rem(rhs));
2221             let m = if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) {
2222                 try_opt!(r.checked_add(rhs))
2223             } else {
2224                 r
2225             };
2226
2227             if m == 0 {
2228                 Some(self)
2229             } else {
2230                 self.checked_add(try_opt!(rhs.checked_sub(m)))
2231             }
2232         }
2233
2234         /// Returns the logarithm of the number with respect to an arbitrary base,
2235         /// rounded down.
2236         ///
2237         /// This method might not be optimized owing to implementation details;
2238         /// `log2` can produce results more efficiently for base 2, and `log10`
2239         /// can produce results more efficiently for base 10.
2240         ///
2241         /// # Panics
2242         ///
2243         /// When the number is zero, or if the base is not at least 2; it
2244         /// panics in debug mode and the return value is 0 in release
2245         /// mode.
2246         ///
2247         /// # Examples
2248         ///
2249         /// ```
2250         /// #![feature(int_log)]
2251         #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".log(5), 1);")]
2252         /// ```
2253         #[unstable(feature = "int_log", issue = "70887")]
2254         #[must_use = "this returns the result of the operation, \
2255                       without modifying the original"]
2256         #[inline]
2257         #[track_caller]
2258         #[rustc_inherit_overflow_checks]
2259         #[allow(arithmetic_overflow)]
2260         pub const fn log(self, base: Self) -> u32 {
2261             match self.checked_log(base) {
2262                 Some(n) => n,
2263                 None => {
2264                     // In debug builds, trigger a panic on None.
2265                     // This should optimize completely out in release builds.
2266                     let _ = Self::MAX + 1;
2267
2268                     0
2269                 },
2270             }
2271         }
2272
2273         /// Returns the base 2 logarithm of the number, rounded down.
2274         ///
2275         /// # Panics
2276         ///
2277         /// When the number is zero it panics in debug mode and the return value
2278         /// is 0 in release mode.
2279         ///
2280         /// # Examples
2281         ///
2282         /// ```
2283         /// #![feature(int_log)]
2284         #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".log2(), 1);")]
2285         /// ```
2286         #[unstable(feature = "int_log", issue = "70887")]
2287         #[must_use = "this returns the result of the operation, \
2288                       without modifying the original"]
2289         #[inline]
2290         #[track_caller]
2291         #[rustc_inherit_overflow_checks]
2292         #[allow(arithmetic_overflow)]
2293         pub const fn log2(self) -> u32 {
2294             match self.checked_log2() {
2295                 Some(n) => n,
2296                 None => {
2297                     // In debug builds, trigger a panic on None.
2298                     // This should optimize completely out in release builds.
2299                     let _ = Self::MAX + 1;
2300
2301                     0
2302                 },
2303             }
2304         }
2305
2306         /// Returns the base 10 logarithm of the number, rounded down.
2307         ///
2308         /// # Panics
2309         ///
2310         /// When the number is zero it panics in debug mode and the return value
2311         /// is 0 in release mode.
2312         ///
2313         /// # Example
2314         ///
2315         /// ```
2316         /// #![feature(int_log)]
2317         #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".log10(), 1);")]
2318         /// ```
2319         #[unstable(feature = "int_log", issue = "70887")]
2320         #[must_use = "this returns the result of the operation, \
2321                       without modifying the original"]
2322         #[inline]
2323         #[track_caller]
2324         #[rustc_inherit_overflow_checks]
2325         #[allow(arithmetic_overflow)]
2326         pub const fn log10(self) -> u32 {
2327             match self.checked_log10() {
2328                 Some(n) => n,
2329                 None => {
2330                     // In debug builds, trigger a panic on None.
2331                     // This should optimize completely out in release builds.
2332                     let _ = Self::MAX + 1;
2333
2334                     0
2335                 },
2336             }
2337         }
2338
2339         /// Returns the logarithm of the number with respect to an arbitrary base,
2340         /// rounded down.
2341         ///
2342         /// Returns `None` if the number is negative or zero, or if the base is not at least 2.
2343         ///
2344         /// This method might not be optimized owing to implementation details;
2345         /// `checked_log2` can produce results more efficiently for base 2, and
2346         /// `checked_log10` can produce results more efficiently for base 10.
2347         ///
2348         /// # Examples
2349         ///
2350         /// ```
2351         /// #![feature(int_log)]
2352         #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_log(5), Some(1));")]
2353         /// ```
2354         #[unstable(feature = "int_log", issue = "70887")]
2355         #[must_use = "this returns the result of the operation, \
2356                       without modifying the original"]
2357         #[inline]
2358         pub const fn checked_log(self, base: Self) -> Option<u32> {
2359             if self <= 0 || base <= 1 {
2360                 None
2361             } else {
2362                 let mut n = 0;
2363                 let mut r = self;
2364
2365                 // Optimization for 128 bit wide integers.
2366                 if Self::BITS == 128 {
2367                     let b = Self::log2(self) / (Self::log2(base) + 1);
2368                     n += b;
2369                     r /= base.pow(b as u32);
2370                 }
2371
2372                 while r >= base {
2373                     r /= base;
2374                     n += 1;
2375                 }
2376                 Some(n)
2377             }
2378         }
2379
2380         /// Returns the base 2 logarithm of the number, rounded down.
2381         ///
2382         /// Returns `None` if the number is negative or zero.
2383         ///
2384         /// # Examples
2385         ///
2386         /// ```
2387         /// #![feature(int_log)]
2388         #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_log2(), Some(1));")]
2389         /// ```
2390         #[unstable(feature = "int_log", issue = "70887")]
2391         #[must_use = "this returns the result of the operation, \
2392                       without modifying the original"]
2393         #[inline]
2394         pub const fn checked_log2(self) -> Option<u32> {
2395             if self <= 0 {
2396                 None
2397             } else {
2398                 // SAFETY: We just checked that this number is positive
2399                 let log = (Self::BITS - 1) - unsafe { intrinsics::ctlz_nonzero(self) as u32 };
2400                 Some(log)
2401             }
2402         }
2403
2404         /// Returns the base 10 logarithm of the number, rounded down.
2405         ///
2406         /// Returns `None` if the number is negative or zero.
2407         ///
2408         /// # Example
2409         ///
2410         /// ```
2411         /// #![feature(int_log)]
2412         #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_log10(), Some(1));")]
2413         /// ```
2414         #[unstable(feature = "int_log", issue = "70887")]
2415         #[must_use = "this returns the result of the operation, \
2416                       without modifying the original"]
2417         #[inline]
2418         pub const fn checked_log10(self) -> Option<u32> {
2419             int_log10::$ActualT(self as $ActualT)
2420         }
2421
2422         /// Computes the absolute value of `self`.
2423         ///
2424         /// # Overflow behavior
2425         ///
2426         /// The absolute value of
2427         #[doc = concat!("`", stringify!($SelfT), "::MIN`")]
2428         /// cannot be represented as an
2429         #[doc = concat!("`", stringify!($SelfT), "`,")]
2430         /// and attempting to calculate it will cause an overflow. This means
2431         /// that code in debug mode will trigger a panic on this case and
2432         /// optimized code will return
2433         #[doc = concat!("`", stringify!($SelfT), "::MIN`")]
2434         /// without a panic.
2435         ///
2436         /// # Examples
2437         ///
2438         /// Basic usage:
2439         ///
2440         /// ```
2441         #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".abs(), 10);")]
2442         #[doc = concat!("assert_eq!((-10", stringify!($SelfT), ").abs(), 10);")]
2443         /// ```
2444         #[stable(feature = "rust1", since = "1.0.0")]
2445         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2446         #[allow(unused_attributes)]
2447         #[must_use = "this returns the result of the operation, \
2448                       without modifying the original"]
2449         #[inline]
2450         #[rustc_inherit_overflow_checks]
2451         pub const fn abs(self) -> Self {
2452             // Note that the #[rustc_inherit_overflow_checks] and #[inline]
2453             // above mean that the overflow semantics of the subtraction
2454             // depend on the crate we're being called from.
2455             if self.is_negative() {
2456                 -self
2457             } else {
2458                 self
2459             }
2460         }
2461
2462         /// Computes the absolute difference between `self` and `other`.
2463         ///
2464         /// This function always returns the correct answer without overflow or
2465         /// panics by returning an unsigned integer.
2466         ///
2467         /// # Examples
2468         ///
2469         /// Basic usage:
2470         ///
2471         /// ```
2472         /// #![feature(int_abs_diff)]
2473         #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(80), 20", stringify!($UnsignedT), ");")]
2474         #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(110), 10", stringify!($UnsignedT), ");")]
2475         #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").abs_diff(80), 180", stringify!($UnsignedT), ");")]
2476         #[doc = concat!("assert_eq!((-100", stringify!($SelfT), ").abs_diff(-120), 20", stringify!($UnsignedT), ");")]
2477         #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN.abs_diff(", stringify!($SelfT), "::MAX), ", stringify!($UnsignedT), "::MAX);")]
2478         /// ```
2479         #[unstable(feature = "int_abs_diff", issue = "89492")]
2480         #[must_use = "this returns the result of the operation, \
2481                       without modifying the original"]
2482         #[inline]
2483         pub const fn abs_diff(self, other: Self) -> $UnsignedT {
2484             if self < other {
2485                 // Converting a non-negative x from signed to unsigned by using
2486                 // `x as U` is left unchanged, but a negative x is converted
2487                 // to value x + 2^N. Thus if `s` and `o` are binary variables
2488                 // respectively indicating whether `self` and `other` are
2489                 // negative, we are computing the mathematical value:
2490                 //
2491                 //    (other + o*2^N) - (self + s*2^N)    mod  2^N
2492                 //    other - self + (o-s)*2^N            mod  2^N
2493                 //    other - self                        mod  2^N
2494                 //
2495                 // Finally, taking the mod 2^N of the mathematical value of
2496                 // `other - self` does not change it as it already is
2497                 // in the range [0, 2^N).
2498                 (other as $UnsignedT).wrapping_sub(self as $UnsignedT)
2499             } else {
2500                 (self as $UnsignedT).wrapping_sub(other as $UnsignedT)
2501             }
2502         }
2503
2504         /// Returns a number representing sign of `self`.
2505         ///
2506         ///  - `0` if the number is zero
2507         ///  - `1` if the number is positive
2508         ///  - `-1` if the number is negative
2509         ///
2510         /// # Examples
2511         ///
2512         /// Basic usage:
2513         ///
2514         /// ```
2515         #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".signum(), 1);")]
2516         #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".signum(), 0);")]
2517         #[doc = concat!("assert_eq!((-10", stringify!($SelfT), ").signum(), -1);")]
2518         /// ```
2519         #[stable(feature = "rust1", since = "1.0.0")]
2520         #[rustc_const_stable(feature = "const_int_sign", since = "1.47.0")]
2521         #[must_use = "this returns the result of the operation, \
2522                       without modifying the original"]
2523         #[inline(always)]
2524         pub const fn signum(self) -> Self {
2525             match self {
2526                 n if n > 0 =>  1,
2527                 0          =>  0,
2528                 _          => -1,
2529             }
2530         }
2531
2532         /// Returns `true` if `self` is positive and `false` if the number is zero or
2533         /// negative.
2534         ///
2535         /// # Examples
2536         ///
2537         /// Basic usage:
2538         ///
2539         /// ```
2540         #[doc = concat!("assert!(10", stringify!($SelfT), ".is_positive());")]
2541         #[doc = concat!("assert!(!(-10", stringify!($SelfT), ").is_positive());")]
2542         /// ```
2543         #[must_use]
2544         #[stable(feature = "rust1", since = "1.0.0")]
2545         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2546         #[inline(always)]
2547         pub const fn is_positive(self) -> bool { self > 0 }
2548
2549         /// Returns `true` if `self` is negative and `false` if the number is zero or
2550         /// positive.
2551         ///
2552         /// # Examples
2553         ///
2554         /// Basic usage:
2555         ///
2556         /// ```
2557         #[doc = concat!("assert!((-10", stringify!($SelfT), ").is_negative());")]
2558         #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_negative());")]
2559         /// ```
2560         #[must_use]
2561         #[stable(feature = "rust1", since = "1.0.0")]
2562         #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
2563         #[inline(always)]
2564         pub const fn is_negative(self) -> bool { self < 0 }
2565
2566         /// Return the memory representation of this integer as a byte array in
2567         /// big-endian (network) byte order.
2568         ///
2569         #[doc = $to_xe_bytes_doc]
2570         ///
2571         /// # Examples
2572         ///
2573         /// ```
2574         #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();")]
2575         #[doc = concat!("assert_eq!(bytes, ", $be_bytes, ");")]
2576         /// ```
2577         #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2578         #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2579         #[must_use = "this returns the result of the operation, \
2580                       without modifying the original"]
2581         #[inline]
2582         pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2583             self.to_be().to_ne_bytes()
2584         }
2585
2586         /// Return the memory representation of this integer as a byte array in
2587         /// little-endian byte order.
2588         ///
2589         #[doc = $to_xe_bytes_doc]
2590         ///
2591         /// # Examples
2592         ///
2593         /// ```
2594         #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();")]
2595         #[doc = concat!("assert_eq!(bytes, ", $le_bytes, ");")]
2596         /// ```
2597         #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2598         #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2599         #[must_use = "this returns the result of the operation, \
2600                       without modifying the original"]
2601         #[inline]
2602         pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2603             self.to_le().to_ne_bytes()
2604         }
2605
2606         /// Return the memory representation of this integer as a byte array in
2607         /// native byte order.
2608         ///
2609         /// As the target platform's native endianness is used, portable code
2610         /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2611         /// instead.
2612         ///
2613         #[doc = $to_xe_bytes_doc]
2614         ///
2615         /// [`to_be_bytes`]: Self::to_be_bytes
2616         /// [`to_le_bytes`]: Self::to_le_bytes
2617         ///
2618         /// # Examples
2619         ///
2620         /// ```
2621         #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();")]
2622         /// assert_eq!(
2623         ///     bytes,
2624         ///     if cfg!(target_endian = "big") {
2625         #[doc = concat!("        ", $be_bytes)]
2626         ///     } else {
2627         #[doc = concat!("        ", $le_bytes)]
2628         ///     }
2629         /// );
2630         /// ```
2631         #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2632         #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2633         // SAFETY: const sound because integers are plain old datatypes so we can always
2634         // transmute them to arrays of bytes
2635         #[must_use = "this returns the result of the operation, \
2636                       without modifying the original"]
2637         #[inline]
2638         pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2639             // SAFETY: integers are plain old datatypes so we can always transmute them to
2640             // arrays of bytes
2641             unsafe { mem::transmute(self) }
2642         }
2643
2644         /// Create an integer value from its representation as a byte array in
2645         /// big endian.
2646         ///
2647         #[doc = $to_xe_bytes_doc]
2648         ///
2649         /// # Examples
2650         ///
2651         /// ```
2652         #[doc = concat!("let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");")]
2653         #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2654         /// ```
2655         ///
2656         /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2657         ///
2658         /// ```
2659         /// use std::convert::TryInto;
2660         ///
2661         #[doc = concat!("fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2662         #[doc = concat!("    let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2663         ///     *input = rest;
2664         #[doc = concat!("    ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())")]
2665         /// }
2666         /// ```
2667         #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2668         #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2669         #[must_use]
2670         #[inline]
2671         pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2672             Self::from_be(Self::from_ne_bytes(bytes))
2673         }
2674
2675         /// Create an integer value from its representation as a byte array in
2676         /// little endian.
2677         ///
2678         #[doc = $to_xe_bytes_doc]
2679         ///
2680         /// # Examples
2681         ///
2682         /// ```
2683         #[doc = concat!("let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");")]
2684         #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2685         /// ```
2686         ///
2687         /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2688         ///
2689         /// ```
2690         /// use std::convert::TryInto;
2691         ///
2692         #[doc = concat!("fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2693         #[doc = concat!("    let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2694         ///     *input = rest;
2695         #[doc = concat!("    ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())")]
2696         /// }
2697         /// ```
2698         #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2699         #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2700         #[must_use]
2701         #[inline]
2702         pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2703             Self::from_le(Self::from_ne_bytes(bytes))
2704         }
2705
2706         /// Create an integer value from its memory representation as a byte
2707         /// array in native endianness.
2708         ///
2709         /// As the target platform's native endianness is used, portable code
2710         /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2711         /// appropriate instead.
2712         ///
2713         /// [`from_be_bytes`]: Self::from_be_bytes
2714         /// [`from_le_bytes`]: Self::from_le_bytes
2715         ///
2716         #[doc = $to_xe_bytes_doc]
2717         ///
2718         /// # Examples
2719         ///
2720         /// ```
2721         #[doc = concat!("let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {")]
2722         #[doc = concat!("    ", $be_bytes)]
2723         /// } else {
2724         #[doc = concat!("    ", $le_bytes)]
2725         /// });
2726         #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
2727         /// ```
2728         ///
2729         /// When starting from a slice rather than an array, fallible conversion APIs can be used:
2730         ///
2731         /// ```
2732         /// use std::convert::TryInto;
2733         ///
2734         #[doc = concat!("fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
2735         #[doc = concat!("    let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
2736         ///     *input = rest;
2737         #[doc = concat!("    ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())")]
2738         /// }
2739         /// ```
2740         #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
2741         #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
2742         #[must_use]
2743         // SAFETY: const sound because integers are plain old datatypes so we can always
2744         // transmute to them
2745         #[inline]
2746         pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2747             // SAFETY: integers are plain old datatypes so we can always transmute to them
2748             unsafe { mem::transmute(bytes) }
2749         }
2750
2751         /// New code should prefer to use
2752         #[doc = concat!("[`", stringify!($SelfT), "::MIN", "`] instead.")]
2753         ///
2754         /// Returns the smallest value that can be represented by this integer type.
2755         #[stable(feature = "rust1", since = "1.0.0")]
2756         #[inline(always)]
2757         #[rustc_promotable]
2758         #[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
2759         #[rustc_deprecated(since = "TBD", reason = "replaced by the `MIN` associated constant on this type")]
2760         pub const fn min_value() -> Self {
2761             Self::MIN
2762         }
2763
2764         /// New code should prefer to use
2765         #[doc = concat!("[`", stringify!($SelfT), "::MAX", "`] instead.")]
2766         ///
2767         /// Returns the largest value that can be represented by this integer type.
2768         #[stable(feature = "rust1", since = "1.0.0")]
2769         #[inline(always)]
2770         #[rustc_promotable]
2771         #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
2772         #[rustc_deprecated(since = "TBD", reason = "replaced by the `MAX` associated constant on this type")]
2773         pub const fn max_value() -> Self {
2774             Self::MAX
2775         }
2776     }
2777 }