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