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