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