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