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