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