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