core/num/uint_macros.rs
1macro_rules! uint_impl {
2 (
3 Self = $SelfT:ty,
4 ActualT = $ActualT:ident,
5 SignedT = $SignedT:ident,
6
7 // These are all for use *only* in doc comments.
8 // As such, they're all passed as literals -- passing them as a string
9 // literal is fine if they need to be multiple code tokens.
10 // In non-comments, use the associated constants rather than these.
11 BITS = $BITS:literal,
12 BITS_MINUS_ONE = $BITS_MINUS_ONE:literal,
13 MAX = $MaxV:literal,
14 rot = $rot:literal,
15 rot_op = $rot_op:literal,
16 rot_result = $rot_result:literal,
17 swap_op = $swap_op:literal,
18 swapped = $swapped:literal,
19 reversed = $reversed:literal,
20 le_bytes = $le_bytes:literal,
21 be_bytes = $be_bytes:literal,
22 to_xe_bytes_doc = $to_xe_bytes_doc:expr,
23 from_xe_bytes_doc = $from_xe_bytes_doc:expr,
24 bound_condition = $bound_condition:literal,
25 ) => {
26 /// The smallest value that can be represented by this integer type.
27 ///
28 /// # Examples
29 ///
30 /// Basic usage:
31 ///
32 /// ```
33 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN, 0);")]
34 /// ```
35 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
36 pub const MIN: Self = 0;
37
38 /// The largest value that can be represented by this integer type
39 #[doc = concat!("(2<sup>", $BITS, "</sup> − 1", $bound_condition, ").")]
40 ///
41 /// # Examples
42 ///
43 /// Basic usage:
44 ///
45 /// ```
46 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($MaxV), ");")]
47 /// ```
48 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
49 pub const MAX: Self = !0;
50
51 /// The size of this integer type in bits.
52 ///
53 /// # Examples
54 ///
55 /// ```
56 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::BITS, ", stringify!($BITS), ");")]
57 /// ```
58 #[stable(feature = "int_bits_const", since = "1.53.0")]
59 pub const BITS: u32 = Self::MAX.count_ones();
60
61 /// Returns the number of ones in the binary representation of `self`.
62 ///
63 /// # Examples
64 ///
65 /// Basic usage:
66 ///
67 /// ```
68 #[doc = concat!("let n = 0b01001100", stringify!($SelfT), ";")]
69 /// assert_eq!(n.count_ones(), 3);
70 ///
71 #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")]
72 #[doc = concat!("assert_eq!(max.count_ones(), ", stringify!($BITS), ");")]
73 ///
74 #[doc = concat!("let zero = 0", stringify!($SelfT), ";")]
75 /// assert_eq!(zero.count_ones(), 0);
76 /// ```
77 #[stable(feature = "rust1", since = "1.0.0")]
78 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
79 #[doc(alias = "popcount")]
80 #[doc(alias = "popcnt")]
81 #[must_use = "this returns the result of the operation, \
82 without modifying the original"]
83 #[inline(always)]
84 pub const fn count_ones(self) -> u32 {
85 return intrinsics::ctpop(self);
86 }
87
88 /// Returns the number of zeros in the binary representation of `self`.
89 ///
90 /// # Examples
91 ///
92 /// Basic usage:
93 ///
94 /// ```
95 #[doc = concat!("let zero = 0", stringify!($SelfT), ";")]
96 #[doc = concat!("assert_eq!(zero.count_zeros(), ", stringify!($BITS), ");")]
97 ///
98 #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")]
99 /// assert_eq!(max.count_zeros(), 0);
100 /// ```
101 #[stable(feature = "rust1", since = "1.0.0")]
102 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
103 #[must_use = "this returns the result of the operation, \
104 without modifying the original"]
105 #[inline(always)]
106 pub const fn count_zeros(self) -> u32 {
107 (!self).count_ones()
108 }
109
110 /// Returns the number of leading zeros in the binary representation of `self`.
111 ///
112 /// Depending on what you're doing with the value, you might also be interested in the
113 /// [`ilog2`] function which returns a consistent number, even if the type widens.
114 ///
115 /// # Examples
116 ///
117 /// Basic usage:
118 ///
119 /// ```
120 #[doc = concat!("let n = ", stringify!($SelfT), "::MAX >> 2;")]
121 /// assert_eq!(n.leading_zeros(), 2);
122 ///
123 #[doc = concat!("let zero = 0", stringify!($SelfT), ";")]
124 #[doc = concat!("assert_eq!(zero.leading_zeros(), ", stringify!($BITS), ");")]
125 ///
126 #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")]
127 /// assert_eq!(max.leading_zeros(), 0);
128 /// ```
129 #[doc = concat!("[`ilog2`]: ", stringify!($SelfT), "::ilog2")]
130 #[stable(feature = "rust1", since = "1.0.0")]
131 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
132 #[must_use = "this returns the result of the operation, \
133 without modifying the original"]
134 #[inline(always)]
135 pub const fn leading_zeros(self) -> u32 {
136 return intrinsics::ctlz(self as $ActualT);
137 }
138
139 /// Returns the number of trailing zeros in the binary representation
140 /// of `self`.
141 ///
142 /// # Examples
143 ///
144 /// Basic usage:
145 ///
146 /// ```
147 #[doc = concat!("let n = 0b0101000", stringify!($SelfT), ";")]
148 /// assert_eq!(n.trailing_zeros(), 3);
149 ///
150 #[doc = concat!("let zero = 0", stringify!($SelfT), ";")]
151 #[doc = concat!("assert_eq!(zero.trailing_zeros(), ", stringify!($BITS), ");")]
152 ///
153 #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")]
154 #[doc = concat!("assert_eq!(max.trailing_zeros(), 0);")]
155 /// ```
156 #[stable(feature = "rust1", since = "1.0.0")]
157 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
158 #[must_use = "this returns the result of the operation, \
159 without modifying the original"]
160 #[inline(always)]
161 pub const fn trailing_zeros(self) -> u32 {
162 return intrinsics::cttz(self);
163 }
164
165 /// Returns the number of leading ones in the binary representation of `self`.
166 ///
167 /// # Examples
168 ///
169 /// Basic usage:
170 ///
171 /// ```
172 #[doc = concat!("let n = !(", stringify!($SelfT), "::MAX >> 2);")]
173 /// assert_eq!(n.leading_ones(), 2);
174 ///
175 #[doc = concat!("let zero = 0", stringify!($SelfT), ";")]
176 /// assert_eq!(zero.leading_ones(), 0);
177 ///
178 #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")]
179 #[doc = concat!("assert_eq!(max.leading_ones(), ", stringify!($BITS), ");")]
180 /// ```
181 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
182 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
183 #[must_use = "this returns the result of the operation, \
184 without modifying the original"]
185 #[inline(always)]
186 pub const fn leading_ones(self) -> u32 {
187 (!self).leading_zeros()
188 }
189
190 /// Returns the number of trailing ones in the binary representation
191 /// of `self`.
192 ///
193 /// # Examples
194 ///
195 /// Basic usage:
196 ///
197 /// ```
198 #[doc = concat!("let n = 0b1010111", stringify!($SelfT), ";")]
199 /// assert_eq!(n.trailing_ones(), 3);
200 ///
201 #[doc = concat!("let zero = 0", stringify!($SelfT), ";")]
202 /// assert_eq!(zero.trailing_ones(), 0);
203 ///
204 #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")]
205 #[doc = concat!("assert_eq!(max.trailing_ones(), ", stringify!($BITS), ");")]
206 /// ```
207 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
208 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
209 #[must_use = "this returns the result of the operation, \
210 without modifying the original"]
211 #[inline(always)]
212 pub const fn trailing_ones(self) -> u32 {
213 (!self).trailing_zeros()
214 }
215
216 /// Returns the bit pattern of `self` reinterpreted as a signed integer of the same size.
217 ///
218 /// This produces the same result as an `as` cast, but ensures that the bit-width remains
219 /// the same.
220 ///
221 /// # Examples
222 ///
223 /// Basic usage:
224 ///
225 /// ```
226 #[doc = concat!("let n = ", stringify!($SelfT), "::MAX;")]
227 ///
228 #[doc = concat!("assert_eq!(n.cast_signed(), -1", stringify!($SignedT), ");")]
229 /// ```
230 #[stable(feature = "integer_sign_cast", since = "CURRENT_RUSTC_VERSION")]
231 #[rustc_const_stable(feature = "integer_sign_cast", since = "CURRENT_RUSTC_VERSION")]
232 #[must_use = "this returns the result of the operation, \
233 without modifying the original"]
234 #[inline(always)]
235 pub const fn cast_signed(self) -> $SignedT {
236 self as $SignedT
237 }
238
239 /// Shifts the bits to the left by a specified amount, `n`,
240 /// wrapping the truncated bits to the end of the resulting integer.
241 ///
242 /// Please note this isn't the same operation as the `<<` shifting operator!
243 ///
244 /// # Examples
245 ///
246 /// Basic usage:
247 ///
248 /// ```
249 #[doc = concat!("let n = ", $rot_op, stringify!($SelfT), ";")]
250 #[doc = concat!("let m = ", $rot_result, ";")]
251 ///
252 #[doc = concat!("assert_eq!(n.rotate_left(", $rot, "), m);")]
253 /// ```
254 #[stable(feature = "rust1", since = "1.0.0")]
255 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
256 #[must_use = "this returns the result of the operation, \
257 without modifying the original"]
258 #[inline(always)]
259 pub const fn rotate_left(self, n: u32) -> Self {
260 return intrinsics::rotate_left(self, n);
261 }
262
263 /// Shifts the bits to the right by a specified amount, `n`,
264 /// wrapping the truncated bits to the beginning of the resulting
265 /// integer.
266 ///
267 /// Please note this isn't the same operation as the `>>` shifting operator!
268 ///
269 /// # Examples
270 ///
271 /// Basic usage:
272 ///
273 /// ```
274 #[doc = concat!("let n = ", $rot_result, stringify!($SelfT), ";")]
275 #[doc = concat!("let m = ", $rot_op, ";")]
276 ///
277 #[doc = concat!("assert_eq!(n.rotate_right(", $rot, "), m);")]
278 /// ```
279 #[stable(feature = "rust1", since = "1.0.0")]
280 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
281 #[must_use = "this returns the result of the operation, \
282 without modifying the original"]
283 #[inline(always)]
284 pub const fn rotate_right(self, n: u32) -> Self {
285 return intrinsics::rotate_right(self, n);
286 }
287
288 /// Reverses the byte order of the integer.
289 ///
290 /// # Examples
291 ///
292 /// Basic usage:
293 ///
294 /// ```
295 #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
296 /// let m = n.swap_bytes();
297 ///
298 #[doc = concat!("assert_eq!(m, ", $swapped, ");")]
299 /// ```
300 #[stable(feature = "rust1", since = "1.0.0")]
301 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
302 #[must_use = "this returns the result of the operation, \
303 without modifying the original"]
304 #[inline(always)]
305 pub const fn swap_bytes(self) -> Self {
306 intrinsics::bswap(self as $ActualT) as Self
307 }
308
309 /// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
310 /// second least-significant bit becomes second most-significant bit, etc.
311 ///
312 /// # Examples
313 ///
314 /// Basic usage:
315 ///
316 /// ```
317 #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
318 /// let m = n.reverse_bits();
319 ///
320 #[doc = concat!("assert_eq!(m, ", $reversed, ");")]
321 #[doc = concat!("assert_eq!(0, 0", stringify!($SelfT), ".reverse_bits());")]
322 /// ```
323 #[stable(feature = "reverse_bits", since = "1.37.0")]
324 #[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
325 #[must_use = "this returns the result of the operation, \
326 without modifying the original"]
327 #[inline(always)]
328 pub const fn reverse_bits(self) -> Self {
329 intrinsics::bitreverse(self as $ActualT) as Self
330 }
331
332 /// Converts an integer from big endian to 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 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_be(n), n)")]
346 /// } else {
347 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_be(n), 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 #[must_use]
353 #[inline(always)]
354 pub const fn from_be(x: Self) -> Self {
355 #[cfg(target_endian = "big")]
356 {
357 x
358 }
359 #[cfg(not(target_endian = "big"))]
360 {
361 x.swap_bytes()
362 }
363 }
364
365 /// Converts an integer from little endian to the target's endianness.
366 ///
367 /// On little endian this is a no-op. On big endian the bytes are
368 /// swapped.
369 ///
370 /// # Examples
371 ///
372 /// Basic usage:
373 ///
374 /// ```
375 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
376 ///
377 /// if cfg!(target_endian = "little") {
378 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_le(n), n)")]
379 /// } else {
380 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())")]
381 /// }
382 /// ```
383 #[stable(feature = "rust1", since = "1.0.0")]
384 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
385 #[must_use]
386 #[inline(always)]
387 pub const fn from_le(x: Self) -> Self {
388 #[cfg(target_endian = "little")]
389 {
390 x
391 }
392 #[cfg(not(target_endian = "little"))]
393 {
394 x.swap_bytes()
395 }
396 }
397
398 /// Converts `self` to big endian from the target's endianness.
399 ///
400 /// On big endian this is a no-op. On little endian the bytes are
401 /// swapped.
402 ///
403 /// # Examples
404 ///
405 /// Basic usage:
406 ///
407 /// ```
408 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
409 ///
410 /// if cfg!(target_endian = "big") {
411 /// assert_eq!(n.to_be(), n)
412 /// } else {
413 /// assert_eq!(n.to_be(), n.swap_bytes())
414 /// }
415 /// ```
416 #[stable(feature = "rust1", since = "1.0.0")]
417 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
418 #[must_use = "this returns the result of the operation, \
419 without modifying the original"]
420 #[inline(always)]
421 pub const fn to_be(self) -> Self { // or not to be?
422 #[cfg(target_endian = "big")]
423 {
424 self
425 }
426 #[cfg(not(target_endian = "big"))]
427 {
428 self.swap_bytes()
429 }
430 }
431
432 /// Converts `self` to little endian from the target's endianness.
433 ///
434 /// On little endian this is a no-op. On big endian the bytes are
435 /// swapped.
436 ///
437 /// # Examples
438 ///
439 /// Basic usage:
440 ///
441 /// ```
442 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
443 ///
444 /// if cfg!(target_endian = "little") {
445 /// assert_eq!(n.to_le(), n)
446 /// } else {
447 /// assert_eq!(n.to_le(), n.swap_bytes())
448 /// }
449 /// ```
450 #[stable(feature = "rust1", since = "1.0.0")]
451 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
452 #[must_use = "this returns the result of the operation, \
453 without modifying the original"]
454 #[inline(always)]
455 pub const fn to_le(self) -> Self {
456 #[cfg(target_endian = "little")]
457 {
458 self
459 }
460 #[cfg(not(target_endian = "little"))]
461 {
462 self.swap_bytes()
463 }
464 }
465
466 /// Checked integer addition. Computes `self + rhs`, returning `None`
467 /// if overflow occurred.
468 ///
469 /// # Examples
470 ///
471 /// Basic usage:
472 ///
473 /// ```
474 #[doc = concat!(
475 "assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(1), ",
476 "Some(", stringify!($SelfT), "::MAX - 1));"
477 )]
478 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);")]
479 /// ```
480 #[stable(feature = "rust1", since = "1.0.0")]
481 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
482 #[must_use = "this returns the result of the operation, \
483 without modifying the original"]
484 #[inline]
485 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
486 // This used to use `overflowing_add`, but that means it ends up being
487 // a `wrapping_add`, losing some optimization opportunities. Notably,
488 // phrasing it this way helps `.checked_add(1)` optimize to a check
489 // against `MAX` and a `add nuw`.
490 // Per <https://github.com/rust-lang/rust/pull/124114#issuecomment-2066173305>,
491 // LLVM is happy to re-form the intrinsic later if useful.
492
493 if intrinsics::unlikely(intrinsics::add_with_overflow(self, rhs).1) {
494 None
495 } else {
496 // SAFETY: Just checked it doesn't overflow
497 Some(unsafe { intrinsics::unchecked_add(self, rhs) })
498 }
499 }
500
501 /// Strict integer addition. Computes `self + rhs`, panicking
502 /// if overflow occurred.
503 ///
504 /// # Panics
505 ///
506 /// ## Overflow behavior
507 ///
508 /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
509 ///
510 /// # Examples
511 ///
512 /// Basic usage:
513 ///
514 /// ```
515 /// #![feature(strict_overflow_ops)]
516 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).strict_add(1), ", stringify!($SelfT), "::MAX - 1);")]
517 /// ```
518 ///
519 /// The following panics because of overflow:
520 ///
521 /// ```should_panic
522 /// #![feature(strict_overflow_ops)]
523 #[doc = concat!("let _ = (", stringify!($SelfT), "::MAX - 2).strict_add(3);")]
524 /// ```
525 #[unstable(feature = "strict_overflow_ops", issue = "118260")]
526 #[must_use = "this returns the result of the operation, \
527 without modifying the original"]
528 #[inline]
529 #[track_caller]
530 pub const fn strict_add(self, rhs: Self) -> Self {
531 let (a, b) = self.overflowing_add(rhs);
532 if b { overflow_panic::add() } else { a }
533 }
534
535 /// Unchecked integer addition. Computes `self + rhs`, assuming overflow
536 /// cannot occur.
537 ///
538 /// Calling `x.unchecked_add(y)` is semantically equivalent to calling
539 /// `x.`[`checked_add`]`(y).`[`unwrap_unchecked`]`()`.
540 ///
541 /// If you're just trying to avoid the panic in debug mode, then **do not**
542 /// use this. Instead, you're looking for [`wrapping_add`].
543 ///
544 /// # Safety
545 ///
546 /// This results in undefined behavior when
547 #[doc = concat!("`self + rhs > ", stringify!($SelfT), "::MAX` or `self + rhs < ", stringify!($SelfT), "::MIN`,")]
548 /// i.e. when [`checked_add`] would return `None`.
549 ///
550 /// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
551 #[doc = concat!("[`checked_add`]: ", stringify!($SelfT), "::checked_add")]
552 #[doc = concat!("[`wrapping_add`]: ", stringify!($SelfT), "::wrapping_add")]
553 #[stable(feature = "unchecked_math", since = "1.79.0")]
554 #[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
555 #[must_use = "this returns the result of the operation, \
556 without modifying the original"]
557 #[inline(always)]
558 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
559 pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
560 assert_unsafe_precondition!(
561 check_language_ub,
562 concat!(stringify!($SelfT), "::unchecked_add cannot overflow"),
563 (
564 lhs: $SelfT = self,
565 rhs: $SelfT = rhs,
566 ) => !lhs.overflowing_add(rhs).1,
567 );
568
569 // SAFETY: this is guaranteed to be safe by the caller.
570 unsafe {
571 intrinsics::unchecked_add(self, rhs)
572 }
573 }
574
575 /// Checked addition with a signed integer. Computes `self + rhs`,
576 /// returning `None` if overflow occurred.
577 ///
578 /// # Examples
579 ///
580 /// Basic usage:
581 ///
582 /// ```
583 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_add_signed(2), Some(3));")]
584 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_add_signed(-2), None);")]
585 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add_signed(3), None);")]
586 /// ```
587 #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
588 #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
589 #[must_use = "this returns the result of the operation, \
590 without modifying the original"]
591 #[inline]
592 pub const fn checked_add_signed(self, rhs: $SignedT) -> Option<Self> {
593 let (a, b) = self.overflowing_add_signed(rhs);
594 if intrinsics::unlikely(b) { None } else { Some(a) }
595 }
596
597 /// Strict addition with a signed integer. Computes `self + rhs`,
598 /// panicking if overflow occurred.
599 ///
600 /// # Panics
601 ///
602 /// ## Overflow behavior
603 ///
604 /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
605 ///
606 /// # Examples
607 ///
608 /// Basic usage:
609 ///
610 /// ```
611 /// #![feature(strict_overflow_ops)]
612 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".strict_add_signed(2), 3);")]
613 /// ```
614 ///
615 /// The following panic because of overflow:
616 ///
617 /// ```should_panic
618 /// #![feature(strict_overflow_ops)]
619 #[doc = concat!("let _ = 1", stringify!($SelfT), ".strict_add_signed(-2);")]
620 /// ```
621 ///
622 /// ```should_panic
623 /// #![feature(strict_overflow_ops)]
624 #[doc = concat!("let _ = (", stringify!($SelfT), "::MAX - 2).strict_add_signed(3);")]
625 /// ```
626 #[unstable(feature = "strict_overflow_ops", issue = "118260")]
627 #[must_use = "this returns the result of the operation, \
628 without modifying the original"]
629 #[inline]
630 #[track_caller]
631 pub const fn strict_add_signed(self, rhs: $SignedT) -> Self {
632 let (a, b) = self.overflowing_add_signed(rhs);
633 if b { overflow_panic::add() } else { a }
634 }
635
636 /// Checked integer subtraction. Computes `self - rhs`, returning
637 /// `None` if overflow occurred.
638 ///
639 /// # Examples
640 ///
641 /// Basic usage:
642 ///
643 /// ```
644 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));")]
645 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);")]
646 /// ```
647 #[stable(feature = "rust1", since = "1.0.0")]
648 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
649 #[must_use = "this returns the result of the operation, \
650 without modifying the original"]
651 #[inline]
652 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
653 // Per PR#103299, there's no advantage to the `overflowing` intrinsic
654 // for *unsigned* subtraction and we just emit the manual check anyway.
655 // Thus, rather than using `overflowing_sub` that produces a wrapping
656 // subtraction, check it ourself so we can use an unchecked one.
657
658 if self < rhs {
659 None
660 } else {
661 // SAFETY: just checked this can't overflow
662 Some(unsafe { intrinsics::unchecked_sub(self, rhs) })
663 }
664 }
665
666 /// Strict integer subtraction. Computes `self - rhs`, panicking if
667 /// overflow occurred.
668 ///
669 /// # Panics
670 ///
671 /// ## Overflow behavior
672 ///
673 /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
674 ///
675 /// # Examples
676 ///
677 /// Basic usage:
678 ///
679 /// ```
680 /// #![feature(strict_overflow_ops)]
681 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".strict_sub(1), 0);")]
682 /// ```
683 ///
684 /// The following panics because of overflow:
685 ///
686 /// ```should_panic
687 /// #![feature(strict_overflow_ops)]
688 #[doc = concat!("let _ = 0", stringify!($SelfT), ".strict_sub(1);")]
689 /// ```
690 #[unstable(feature = "strict_overflow_ops", issue = "118260")]
691 #[must_use = "this returns the result of the operation, \
692 without modifying the original"]
693 #[inline]
694 #[track_caller]
695 pub const fn strict_sub(self, rhs: Self) -> Self {
696 let (a, b) = self.overflowing_sub(rhs);
697 if b { overflow_panic::sub() } else { a }
698 }
699
700 /// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
701 /// cannot occur.
702 ///
703 /// Calling `x.unchecked_sub(y)` is semantically equivalent to calling
704 /// `x.`[`checked_sub`]`(y).`[`unwrap_unchecked`]`()`.
705 ///
706 /// If you're just trying to avoid the panic in debug mode, then **do not**
707 /// use this. Instead, you're looking for [`wrapping_sub`].
708 ///
709 /// If you find yourself writing code like this:
710 ///
711 /// ```
712 /// # let foo = 30_u32;
713 /// # let bar = 20;
714 /// if foo >= bar {
715 /// // SAFETY: just checked it will not overflow
716 /// let diff = unsafe { foo.unchecked_sub(bar) };
717 /// // ... use diff ...
718 /// }
719 /// ```
720 ///
721 /// Consider changing it to
722 ///
723 /// ```
724 /// # let foo = 30_u32;
725 /// # let bar = 20;
726 /// if let Some(diff) = foo.checked_sub(bar) {
727 /// // ... use diff ...
728 /// }
729 /// ```
730 ///
731 /// As that does exactly the same thing -- including telling the optimizer
732 /// that the subtraction cannot overflow -- but avoids needing `unsafe`.
733 ///
734 /// # Safety
735 ///
736 /// This results in undefined behavior when
737 #[doc = concat!("`self - rhs > ", stringify!($SelfT), "::MAX` or `self - rhs < ", stringify!($SelfT), "::MIN`,")]
738 /// i.e. when [`checked_sub`] would return `None`.
739 ///
740 /// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
741 #[doc = concat!("[`checked_sub`]: ", stringify!($SelfT), "::checked_sub")]
742 #[doc = concat!("[`wrapping_sub`]: ", stringify!($SelfT), "::wrapping_sub")]
743 #[stable(feature = "unchecked_math", since = "1.79.0")]
744 #[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
745 #[must_use = "this returns the result of the operation, \
746 without modifying the original"]
747 #[inline(always)]
748 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
749 pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
750 assert_unsafe_precondition!(
751 check_language_ub,
752 concat!(stringify!($SelfT), "::unchecked_sub cannot overflow"),
753 (
754 lhs: $SelfT = self,
755 rhs: $SelfT = rhs,
756 ) => !lhs.overflowing_sub(rhs).1,
757 );
758
759 // SAFETY: this is guaranteed to be safe by the caller.
760 unsafe {
761 intrinsics::unchecked_sub(self, rhs)
762 }
763 }
764
765 /// Checked subtraction with a signed integer. Computes `self - rhs`,
766 /// returning `None` if overflow occurred.
767 ///
768 /// # Examples
769 ///
770 /// Basic usage:
771 ///
772 /// ```
773 /// #![feature(mixed_integer_ops_unsigned_sub)]
774 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_sub_signed(2), None);")]
775 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_sub_signed(-2), Some(3));")]
776 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_sub_signed(-4), None);")]
777 /// ```
778 #[unstable(feature = "mixed_integer_ops_unsigned_sub", issue = "126043")]
779 #[must_use = "this returns the result of the operation, \
780 without modifying the original"]
781 #[inline]
782 pub const fn checked_sub_signed(self, rhs: $SignedT) -> Option<Self> {
783 let (res, overflow) = self.overflowing_sub_signed(rhs);
784
785 if !overflow {
786 Some(res)
787 } else {
788 None
789 }
790 }
791
792 #[doc = concat!(
793 "Checked integer subtraction. Computes `self - rhs` and checks if the result fits into an [`",
794 stringify!($SignedT), "`], returning `None` if overflow occurred."
795 )]
796 ///
797 /// # Examples
798 ///
799 /// Basic usage:
800 ///
801 /// ```
802 /// #![feature(unsigned_signed_diff)]
803 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_signed_diff(2), Some(8));")]
804 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_signed_diff(10), Some(-8));")]
805 #[doc = concat!(
806 "assert_eq!(",
807 stringify!($SelfT),
808 "::MAX.checked_signed_diff(",
809 stringify!($SignedT),
810 "::MAX as ",
811 stringify!($SelfT),
812 "), None);"
813 )]
814 #[doc = concat!(
815 "assert_eq!((",
816 stringify!($SignedT),
817 "::MAX as ",
818 stringify!($SelfT),
819 ").checked_signed_diff(",
820 stringify!($SelfT),
821 "::MAX), Some(",
822 stringify!($SignedT),
823 "::MIN));"
824 )]
825 #[doc = concat!(
826 "assert_eq!((",
827 stringify!($SignedT),
828 "::MAX as ",
829 stringify!($SelfT),
830 " + 1).checked_signed_diff(0), None);"
831 )]
832 #[doc = concat!(
833 "assert_eq!(",
834 stringify!($SelfT),
835 "::MAX.checked_signed_diff(",
836 stringify!($SelfT),
837 "::MAX), Some(0));"
838 )]
839 /// ```
840 #[unstable(feature = "unsigned_signed_diff", issue = "126041")]
841 #[inline]
842 pub const fn checked_signed_diff(self, rhs: Self) -> Option<$SignedT> {
843 let res = self.wrapping_sub(rhs) as $SignedT;
844 let overflow = (self >= rhs) == (res < 0);
845
846 if !overflow {
847 Some(res)
848 } else {
849 None
850 }
851 }
852
853 /// Checked integer multiplication. Computes `self * rhs`, returning
854 /// `None` if overflow occurred.
855 ///
856 /// # Examples
857 ///
858 /// Basic usage:
859 ///
860 /// ```
861 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));")]
862 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);")]
863 /// ```
864 #[stable(feature = "rust1", since = "1.0.0")]
865 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
866 #[must_use = "this returns the result of the operation, \
867 without modifying the original"]
868 #[inline]
869 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
870 let (a, b) = self.overflowing_mul(rhs);
871 if intrinsics::unlikely(b) { None } else { Some(a) }
872 }
873
874 /// Strict integer multiplication. Computes `self * rhs`, panicking if
875 /// overflow occurred.
876 ///
877 /// # Panics
878 ///
879 /// ## Overflow behavior
880 ///
881 /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
882 ///
883 /// # Examples
884 ///
885 /// Basic usage:
886 ///
887 /// ```
888 /// #![feature(strict_overflow_ops)]
889 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".strict_mul(1), 5);")]
890 /// ```
891 ///
892 /// The following panics because of overflow:
893 ///
894 /// ``` should_panic
895 /// #![feature(strict_overflow_ops)]
896 #[doc = concat!("let _ = ", stringify!($SelfT), "::MAX.strict_mul(2);")]
897 /// ```
898 #[unstable(feature = "strict_overflow_ops", issue = "118260")]
899 #[must_use = "this returns the result of the operation, \
900 without modifying the original"]
901 #[inline]
902 #[track_caller]
903 pub const fn strict_mul(self, rhs: Self) -> Self {
904 let (a, b) = self.overflowing_mul(rhs);
905 if b { overflow_panic::mul() } else { a }
906 }
907
908 /// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
909 /// cannot occur.
910 ///
911 /// Calling `x.unchecked_mul(y)` is semantically equivalent to calling
912 /// `x.`[`checked_mul`]`(y).`[`unwrap_unchecked`]`()`.
913 ///
914 /// If you're just trying to avoid the panic in debug mode, then **do not**
915 /// use this. Instead, you're looking for [`wrapping_mul`].
916 ///
917 /// # Safety
918 ///
919 /// This results in undefined behavior when
920 #[doc = concat!("`self * rhs > ", stringify!($SelfT), "::MAX` or `self * rhs < ", stringify!($SelfT), "::MIN`,")]
921 /// i.e. when [`checked_mul`] would return `None`.
922 ///
923 /// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
924 #[doc = concat!("[`checked_mul`]: ", stringify!($SelfT), "::checked_mul")]
925 #[doc = concat!("[`wrapping_mul`]: ", stringify!($SelfT), "::wrapping_mul")]
926 #[stable(feature = "unchecked_math", since = "1.79.0")]
927 #[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
928 #[must_use = "this returns the result of the operation, \
929 without modifying the original"]
930 #[inline(always)]
931 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
932 pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
933 assert_unsafe_precondition!(
934 check_language_ub,
935 concat!(stringify!($SelfT), "::unchecked_mul cannot overflow"),
936 (
937 lhs: $SelfT = self,
938 rhs: $SelfT = rhs,
939 ) => !lhs.overflowing_mul(rhs).1,
940 );
941
942 // SAFETY: this is guaranteed to be safe by the caller.
943 unsafe {
944 intrinsics::unchecked_mul(self, rhs)
945 }
946 }
947
948 /// Checked integer division. Computes `self / rhs`, returning `None`
949 /// if `rhs == 0`.
950 ///
951 /// # Examples
952 ///
953 /// Basic usage:
954 ///
955 /// ```
956 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));")]
957 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);")]
958 /// ```
959 #[stable(feature = "rust1", since = "1.0.0")]
960 #[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
961 #[must_use = "this returns the result of the operation, \
962 without modifying the original"]
963 #[inline]
964 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
965 if intrinsics::unlikely(rhs == 0) {
966 None
967 } else {
968 // SAFETY: div by zero has been checked above and unsigned types have no other
969 // failure modes for division
970 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
971 }
972 }
973
974 /// Strict integer division. Computes `self / rhs`.
975 ///
976 /// Strict division on unsigned types is just normal division. There's no
977 /// way overflow could ever happen. This function exists so that all
978 /// operations are accounted for in the strict operations.
979 ///
980 /// # Panics
981 ///
982 /// This function will panic if `rhs` is zero.
983 ///
984 /// # Examples
985 ///
986 /// Basic usage:
987 ///
988 /// ```
989 /// #![feature(strict_overflow_ops)]
990 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".strict_div(10), 10);")]
991 /// ```
992 ///
993 /// The following panics because of division by zero:
994 ///
995 /// ```should_panic
996 /// #![feature(strict_overflow_ops)]
997 #[doc = concat!("let _ = (1", stringify!($SelfT), ").strict_div(0);")]
998 /// ```
999 #[unstable(feature = "strict_overflow_ops", issue = "118260")]
1000 #[must_use = "this returns the result of the operation, \
1001 without modifying the original"]
1002 #[inline(always)]
1003 #[track_caller]
1004 pub const fn strict_div(self, rhs: Self) -> Self {
1005 self / rhs
1006 }
1007
1008 /// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
1009 /// if `rhs == 0`.
1010 ///
1011 /// # Examples
1012 ///
1013 /// Basic usage:
1014 ///
1015 /// ```
1016 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));")]
1017 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);")]
1018 /// ```
1019 #[stable(feature = "euclidean_division", since = "1.38.0")]
1020 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1021 #[must_use = "this returns the result of the operation, \
1022 without modifying the original"]
1023 #[inline]
1024 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
1025 if intrinsics::unlikely(rhs == 0) {
1026 None
1027 } else {
1028 Some(self.div_euclid(rhs))
1029 }
1030 }
1031
1032 /// Strict Euclidean division. Computes `self.div_euclid(rhs)`.
1033 ///
1034 /// Strict division on unsigned types is just normal division. There's no
1035 /// way overflow could ever happen. This function exists so that all
1036 /// operations are accounted for in the strict operations. Since, for the
1037 /// positive integers, all common definitions of division are equal, this
1038 /// is exactly equal to `self.strict_div(rhs)`.
1039 ///
1040 /// # Panics
1041 ///
1042 /// This function will panic if `rhs` is zero.
1043 ///
1044 /// # Examples
1045 ///
1046 /// Basic usage:
1047 ///
1048 /// ```
1049 /// #![feature(strict_overflow_ops)]
1050 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".strict_div_euclid(10), 10);")]
1051 /// ```
1052 /// The following panics because of division by zero:
1053 ///
1054 /// ```should_panic
1055 /// #![feature(strict_overflow_ops)]
1056 #[doc = concat!("let _ = (1", stringify!($SelfT), ").strict_div_euclid(0);")]
1057 /// ```
1058 #[unstable(feature = "strict_overflow_ops", issue = "118260")]
1059 #[must_use = "this returns the result of the operation, \
1060 without modifying the original"]
1061 #[inline(always)]
1062 #[track_caller]
1063 pub const fn strict_div_euclid(self, rhs: Self) -> Self {
1064 self / rhs
1065 }
1066
1067 /// Checked integer remainder. Computes `self % rhs`, returning `None`
1068 /// if `rhs == 0`.
1069 ///
1070 /// # Examples
1071 ///
1072 /// Basic usage:
1073 ///
1074 /// ```
1075 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));")]
1076 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);")]
1077 /// ```
1078 #[stable(feature = "wrapping", since = "1.7.0")]
1079 #[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
1080 #[must_use = "this returns the result of the operation, \
1081 without modifying the original"]
1082 #[inline]
1083 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
1084 if intrinsics::unlikely(rhs == 0) {
1085 None
1086 } else {
1087 // SAFETY: div by zero has been checked above and unsigned types have no other
1088 // failure modes for division
1089 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
1090 }
1091 }
1092
1093 /// Strict integer remainder. Computes `self % rhs`.
1094 ///
1095 /// Strict remainder calculation on unsigned types is just the regular
1096 /// remainder calculation. There's no way overflow could ever happen.
1097 /// This function exists so that all operations are accounted for in the
1098 /// strict operations.
1099 ///
1100 /// # Panics
1101 ///
1102 /// This function will panic if `rhs` is zero.
1103 ///
1104 /// # Examples
1105 ///
1106 /// Basic usage:
1107 ///
1108 /// ```
1109 /// #![feature(strict_overflow_ops)]
1110 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".strict_rem(10), 0);")]
1111 /// ```
1112 ///
1113 /// The following panics because of division by zero:
1114 ///
1115 /// ```should_panic
1116 /// #![feature(strict_overflow_ops)]
1117 #[doc = concat!("let _ = 5", stringify!($SelfT), ".strict_rem(0);")]
1118 /// ```
1119 #[unstable(feature = "strict_overflow_ops", issue = "118260")]
1120 #[must_use = "this returns the result of the operation, \
1121 without modifying the original"]
1122 #[inline(always)]
1123 #[track_caller]
1124 pub const fn strict_rem(self, rhs: Self) -> Self {
1125 self % rhs
1126 }
1127
1128 /// Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
1129 /// if `rhs == 0`.
1130 ///
1131 /// # Examples
1132 ///
1133 /// Basic usage:
1134 ///
1135 /// ```
1136 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));")]
1137 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);")]
1138 /// ```
1139 #[stable(feature = "euclidean_division", since = "1.38.0")]
1140 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1141 #[must_use = "this returns the result of the operation, \
1142 without modifying the original"]
1143 #[inline]
1144 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
1145 if intrinsics::unlikely(rhs == 0) {
1146 None
1147 } else {
1148 Some(self.rem_euclid(rhs))
1149 }
1150 }
1151
1152 /// Strict Euclidean modulo. Computes `self.rem_euclid(rhs)`.
1153 ///
1154 /// Strict modulo calculation on unsigned types is just the regular
1155 /// remainder calculation. There's no way overflow could ever happen.
1156 /// This function exists so that all operations are accounted for in the
1157 /// strict operations. Since, for the positive integers, all common
1158 /// definitions of division are equal, this is exactly equal to
1159 /// `self.strict_rem(rhs)`.
1160 ///
1161 /// # Panics
1162 ///
1163 /// This function will panic if `rhs` is zero.
1164 ///
1165 /// # Examples
1166 ///
1167 /// Basic usage:
1168 ///
1169 /// ```
1170 /// #![feature(strict_overflow_ops)]
1171 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".strict_rem_euclid(10), 0);")]
1172 /// ```
1173 ///
1174 /// The following panics because of division by zero:
1175 ///
1176 /// ```should_panic
1177 /// #![feature(strict_overflow_ops)]
1178 #[doc = concat!("let _ = 5", stringify!($SelfT), ".strict_rem_euclid(0);")]
1179 /// ```
1180 #[unstable(feature = "strict_overflow_ops", issue = "118260")]
1181 #[must_use = "this returns the result of the operation, \
1182 without modifying the original"]
1183 #[inline(always)]
1184 #[track_caller]
1185 pub const fn strict_rem_euclid(self, rhs: Self) -> Self {
1186 self % rhs
1187 }
1188
1189 /// Same value as `self | other`, but UB if any bit position is set in both inputs.
1190 ///
1191 /// This is a situational micro-optimization for places where you'd rather
1192 /// use addition on some platforms and bitwise or on other platforms, based
1193 /// on exactly which instructions combine better with whatever else you're
1194 /// doing. Note that there's no reason to bother using this for places
1195 /// where it's clear from the operations involved that they can't overlap.
1196 /// For example, if you're combining `u16`s into a `u32` with
1197 /// `((a as u32) << 16) | (b as u32)`, that's fine, as the backend will
1198 /// know those sides of the `|` are disjoint without needing help.
1199 ///
1200 /// # Examples
1201 ///
1202 /// ```
1203 /// #![feature(disjoint_bitor)]
1204 ///
1205 /// // SAFETY: `1` and `4` have no bits in common.
1206 /// unsafe {
1207 #[doc = concat!(" assert_eq!(1_", stringify!($SelfT), ".unchecked_disjoint_bitor(4), 5);")]
1208 /// }
1209 /// ```
1210 ///
1211 /// # Safety
1212 ///
1213 /// Requires that `(self & other) == 0`, otherwise it's immediate UB.
1214 ///
1215 /// Equivalently, requires that `(self | other) == (self + other)`.
1216 #[unstable(feature = "disjoint_bitor", issue = "135758")]
1217 #[rustc_const_unstable(feature = "disjoint_bitor", issue = "135758")]
1218 #[inline]
1219 pub const unsafe fn unchecked_disjoint_bitor(self, other: Self) -> Self {
1220 assert_unsafe_precondition!(
1221 check_language_ub,
1222 concat!(stringify!($SelfT), "::unchecked_disjoint_bitor cannot have overlapping bits"),
1223 (
1224 lhs: $SelfT = self,
1225 rhs: $SelfT = other,
1226 ) => (lhs & rhs) == 0,
1227 );
1228
1229 // SAFETY: Same precondition
1230 unsafe { intrinsics::disjoint_bitor(self, other) }
1231 }
1232
1233 /// Returns the logarithm of the number with respect to an arbitrary base,
1234 /// rounded down.
1235 ///
1236 /// This method might not be optimized owing to implementation details;
1237 /// `ilog2` can produce results more efficiently for base 2, and `ilog10`
1238 /// can produce results more efficiently for base 10.
1239 ///
1240 /// # Panics
1241 ///
1242 /// This function will panic if `self` is zero, or if `base` is less than 2.
1243 ///
1244 /// # Examples
1245 ///
1246 /// ```
1247 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".ilog(5), 1);")]
1248 /// ```
1249 #[stable(feature = "int_log", since = "1.67.0")]
1250 #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1251 #[must_use = "this returns the result of the operation, \
1252 without modifying the original"]
1253 #[inline]
1254 #[track_caller]
1255 pub const fn ilog(self, base: Self) -> u32 {
1256 assert!(base >= 2, "base of integer logarithm must be at least 2");
1257 if let Some(log) = self.checked_ilog(base) {
1258 log
1259 } else {
1260 int_log10::panic_for_nonpositive_argument()
1261 }
1262 }
1263
1264 /// Returns the base 2 logarithm of the number, rounded down.
1265 ///
1266 /// # Panics
1267 ///
1268 /// This function will panic if `self` is zero.
1269 ///
1270 /// # Examples
1271 ///
1272 /// ```
1273 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".ilog2(), 1);")]
1274 /// ```
1275 #[stable(feature = "int_log", since = "1.67.0")]
1276 #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1277 #[must_use = "this returns the result of the operation, \
1278 without modifying the original"]
1279 #[inline]
1280 #[track_caller]
1281 pub const fn ilog2(self) -> u32 {
1282 if let Some(log) = self.checked_ilog2() {
1283 log
1284 } else {
1285 int_log10::panic_for_nonpositive_argument()
1286 }
1287 }
1288
1289 /// Returns the base 10 logarithm of the number, rounded down.
1290 ///
1291 /// # Panics
1292 ///
1293 /// This function will panic if `self` is zero.
1294 ///
1295 /// # Example
1296 ///
1297 /// ```
1298 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".ilog10(), 1);")]
1299 /// ```
1300 #[stable(feature = "int_log", since = "1.67.0")]
1301 #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1302 #[must_use = "this returns the result of the operation, \
1303 without modifying the original"]
1304 #[inline]
1305 #[track_caller]
1306 pub const fn ilog10(self) -> u32 {
1307 if let Some(log) = self.checked_ilog10() {
1308 log
1309 } else {
1310 int_log10::panic_for_nonpositive_argument()
1311 }
1312 }
1313
1314 /// Returns the logarithm of the number with respect to an arbitrary base,
1315 /// rounded down.
1316 ///
1317 /// Returns `None` if the number is zero, or if the base is not at least 2.
1318 ///
1319 /// This method might not be optimized owing to implementation details;
1320 /// `checked_ilog2` can produce results more efficiently for base 2, and
1321 /// `checked_ilog10` can produce results more efficiently for base 10.
1322 ///
1323 /// # Examples
1324 ///
1325 /// ```
1326 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_ilog(5), Some(1));")]
1327 /// ```
1328 #[stable(feature = "int_log", since = "1.67.0")]
1329 #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1330 #[must_use = "this returns the result of the operation, \
1331 without modifying the original"]
1332 #[inline]
1333 pub const fn checked_ilog(self, base: Self) -> Option<u32> {
1334 if self <= 0 || base <= 1 {
1335 None
1336 } else if self < base {
1337 Some(0)
1338 } else {
1339 // Since base >= self, n >= 1
1340 let mut n = 1;
1341 let mut r = base;
1342
1343 // Optimization for 128 bit wide integers.
1344 if Self::BITS == 128 {
1345 // The following is a correct lower bound for ⌊log(base,self)⌋ because
1346 //
1347 // log(base,self) = log(2,self) / log(2,base)
1348 // ≥ ⌊log(2,self)⌋ / (⌊log(2,base)⌋ + 1)
1349 //
1350 // hence
1351 //
1352 // ⌊log(base,self)⌋ ≥ ⌊ ⌊log(2,self)⌋ / (⌊log(2,base)⌋ + 1) ⌋ .
1353 n = self.ilog2() / (base.ilog2() + 1);
1354 r = base.pow(n);
1355 }
1356
1357 while r <= self / base {
1358 n += 1;
1359 r *= base;
1360 }
1361 Some(n)
1362 }
1363 }
1364
1365 /// Returns the base 2 logarithm of the number, rounded down.
1366 ///
1367 /// Returns `None` if the number is zero.
1368 ///
1369 /// # Examples
1370 ///
1371 /// ```
1372 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_ilog2(), Some(1));")]
1373 /// ```
1374 #[stable(feature = "int_log", since = "1.67.0")]
1375 #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1376 #[must_use = "this returns the result of the operation, \
1377 without modifying the original"]
1378 #[inline]
1379 pub const fn checked_ilog2(self) -> Option<u32> {
1380 match NonZero::new(self) {
1381 Some(x) => Some(x.ilog2()),
1382 None => None,
1383 }
1384 }
1385
1386 /// Returns the base 10 logarithm of the number, rounded down.
1387 ///
1388 /// Returns `None` if the number is zero.
1389 ///
1390 /// # Examples
1391 ///
1392 /// ```
1393 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_ilog10(), Some(1));")]
1394 /// ```
1395 #[stable(feature = "int_log", since = "1.67.0")]
1396 #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1397 #[must_use = "this returns the result of the operation, \
1398 without modifying the original"]
1399 #[inline]
1400 pub const fn checked_ilog10(self) -> Option<u32> {
1401 match NonZero::new(self) {
1402 Some(x) => Some(x.ilog10()),
1403 None => None,
1404 }
1405 }
1406
1407 /// Checked negation. Computes `-self`, returning `None` unless `self ==
1408 /// 0`.
1409 ///
1410 /// Note that negating any positive integer will overflow.
1411 ///
1412 /// # Examples
1413 ///
1414 /// Basic usage:
1415 ///
1416 /// ```
1417 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));")]
1418 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);")]
1419 /// ```
1420 #[stable(feature = "wrapping", since = "1.7.0")]
1421 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
1422 #[must_use = "this returns the result of the operation, \
1423 without modifying the original"]
1424 #[inline]
1425 pub const fn checked_neg(self) -> Option<Self> {
1426 let (a, b) = self.overflowing_neg();
1427 if intrinsics::unlikely(b) { None } else { Some(a) }
1428 }
1429
1430 /// Strict negation. Computes `-self`, panicking unless `self ==
1431 /// 0`.
1432 ///
1433 /// Note that negating any positive integer will overflow.
1434 ///
1435 /// # Panics
1436 ///
1437 /// ## Overflow behavior
1438 ///
1439 /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
1440 ///
1441 /// # Examples
1442 ///
1443 /// Basic usage:
1444 ///
1445 /// ```
1446 /// #![feature(strict_overflow_ops)]
1447 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".strict_neg(), 0);")]
1448 /// ```
1449 ///
1450 /// The following panics because of overflow:
1451 ///
1452 /// ```should_panic
1453 /// #![feature(strict_overflow_ops)]
1454 #[doc = concat!("let _ = 1", stringify!($SelfT), ".strict_neg();")]
1455 ///
1456 #[unstable(feature = "strict_overflow_ops", issue = "118260")]
1457 #[must_use = "this returns the result of the operation, \
1458 without modifying the original"]
1459 #[inline]
1460 #[track_caller]
1461 pub const fn strict_neg(self) -> Self {
1462 let (a, b) = self.overflowing_neg();
1463 if b { overflow_panic::neg() } else { a }
1464 }
1465
1466 /// Checked shift left. Computes `self << rhs`, returning `None`
1467 /// if `rhs` is larger than or equal to the number of bits in `self`.
1468 ///
1469 /// # Examples
1470 ///
1471 /// Basic usage:
1472 ///
1473 /// ```
1474 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));")]
1475 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);")]
1476 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shl(", stringify!($BITS_MINUS_ONE), "), Some(0));")]
1477 /// ```
1478 #[stable(feature = "wrapping", since = "1.7.0")]
1479 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
1480 #[must_use = "this returns the result of the operation, \
1481 without modifying the original"]
1482 #[inline]
1483 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
1484 // Not using overflowing_shl as that's a wrapping shift
1485 if rhs < Self::BITS {
1486 // SAFETY: just checked the RHS is in-range
1487 Some(unsafe { self.unchecked_shl(rhs) })
1488 } else {
1489 None
1490 }
1491 }
1492
1493 /// Strict shift left. Computes `self << rhs`, panicking if `rhs` is larger
1494 /// than or equal to the number of bits in `self`.
1495 ///
1496 /// # Panics
1497 ///
1498 /// ## Overflow behavior
1499 ///
1500 /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
1501 ///
1502 /// # Examples
1503 ///
1504 /// Basic usage:
1505 ///
1506 /// ```
1507 /// #![feature(strict_overflow_ops)]
1508 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".strict_shl(4), 0x10);")]
1509 /// ```
1510 ///
1511 /// The following panics because of overflow:
1512 ///
1513 /// ```should_panic
1514 /// #![feature(strict_overflow_ops)]
1515 #[doc = concat!("let _ = 0x10", stringify!($SelfT), ".strict_shl(129);")]
1516 /// ```
1517 #[unstable(feature = "strict_overflow_ops", issue = "118260")]
1518 #[must_use = "this returns the result of the operation, \
1519 without modifying the original"]
1520 #[inline]
1521 #[track_caller]
1522 pub const fn strict_shl(self, rhs: u32) -> Self {
1523 let (a, b) = self.overflowing_shl(rhs);
1524 if b { overflow_panic::shl() } else { a }
1525 }
1526
1527 /// Unchecked shift left. Computes `self << rhs`, assuming that
1528 /// `rhs` is less than the number of bits in `self`.
1529 ///
1530 /// # Safety
1531 ///
1532 /// This results in undefined behavior if `rhs` is larger than
1533 /// or equal to the number of bits in `self`,
1534 /// i.e. when [`checked_shl`] would return `None`.
1535 ///
1536 #[doc = concat!("[`checked_shl`]: ", stringify!($SelfT), "::checked_shl")]
1537 #[unstable(
1538 feature = "unchecked_shifts",
1539 reason = "niche optimization path",
1540 issue = "85122",
1541 )]
1542 #[must_use = "this returns the result of the operation, \
1543 without modifying the original"]
1544 #[inline(always)]
1545 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1546 pub const unsafe fn unchecked_shl(self, rhs: u32) -> Self {
1547 assert_unsafe_precondition!(
1548 check_language_ub,
1549 concat!(stringify!($SelfT), "::unchecked_shl cannot overflow"),
1550 (
1551 rhs: u32 = rhs,
1552 ) => rhs < <$ActualT>::BITS,
1553 );
1554
1555 // SAFETY: this is guaranteed to be safe by the caller.
1556 unsafe {
1557 intrinsics::unchecked_shl(self, rhs)
1558 }
1559 }
1560
1561 /// Unbounded shift left. Computes `self << rhs`, without bounding the value of `rhs`.
1562 ///
1563 /// If `rhs` is larger or equal to the number of bits in `self`,
1564 /// the entire value is shifted out, and `0` is returned.
1565 ///
1566 /// # Examples
1567 ///
1568 /// Basic usage:
1569 /// ```
1570 /// #![feature(unbounded_shifts)]
1571 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".unbounded_shl(4), 0x10);")]
1572 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".unbounded_shl(129), 0);")]
1573 /// ```
1574 #[unstable(feature = "unbounded_shifts", issue = "129375")]
1575 #[must_use = "this returns the result of the operation, \
1576 without modifying the original"]
1577 #[inline]
1578 pub const fn unbounded_shl(self, rhs: u32) -> $SelfT{
1579 if rhs < Self::BITS {
1580 // SAFETY:
1581 // rhs is just checked to be in-range above
1582 unsafe { self.unchecked_shl(rhs) }
1583 } else {
1584 0
1585 }
1586 }
1587
1588 /// Checked shift right. Computes `self >> rhs`, returning `None`
1589 /// if `rhs` is larger than or equal to the number of bits in `self`.
1590 ///
1591 /// # Examples
1592 ///
1593 /// Basic usage:
1594 ///
1595 /// ```
1596 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));")]
1597 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);")]
1598 /// ```
1599 #[stable(feature = "wrapping", since = "1.7.0")]
1600 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
1601 #[must_use = "this returns the result of the operation, \
1602 without modifying the original"]
1603 #[inline]
1604 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
1605 // Not using overflowing_shr as that's a wrapping shift
1606 if rhs < Self::BITS {
1607 // SAFETY: just checked the RHS is in-range
1608 Some(unsafe { self.unchecked_shr(rhs) })
1609 } else {
1610 None
1611 }
1612 }
1613
1614 /// Strict shift right. Computes `self >> rhs`, panicking `rhs` is
1615 /// larger than or equal to the number of bits in `self`.
1616 ///
1617 /// # Panics
1618 ///
1619 /// ## Overflow behavior
1620 ///
1621 /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
1622 ///
1623 /// # Examples
1624 ///
1625 /// Basic usage:
1626 ///
1627 /// ```
1628 /// #![feature(strict_overflow_ops)]
1629 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".strict_shr(4), 0x1);")]
1630 /// ```
1631 ///
1632 /// The following panics because of overflow:
1633 ///
1634 /// ```should_panic
1635 /// #![feature(strict_overflow_ops)]
1636 #[doc = concat!("let _ = 0x10", stringify!($SelfT), ".strict_shr(129);")]
1637 /// ```
1638 #[unstable(feature = "strict_overflow_ops", issue = "118260")]
1639 #[must_use = "this returns the result of the operation, \
1640 without modifying the original"]
1641 #[inline]
1642 #[track_caller]
1643 pub const fn strict_shr(self, rhs: u32) -> Self {
1644 let (a, b) = self.overflowing_shr(rhs);
1645 if b { overflow_panic::shr() } else { a }
1646 }
1647
1648 /// Unchecked shift right. Computes `self >> rhs`, assuming that
1649 /// `rhs` is less than the number of bits in `self`.
1650 ///
1651 /// # Safety
1652 ///
1653 /// This results in undefined behavior if `rhs` is larger than
1654 /// or equal to the number of bits in `self`,
1655 /// i.e. when [`checked_shr`] would return `None`.
1656 ///
1657 #[doc = concat!("[`checked_shr`]: ", stringify!($SelfT), "::checked_shr")]
1658 #[unstable(
1659 feature = "unchecked_shifts",
1660 reason = "niche optimization path",
1661 issue = "85122",
1662 )]
1663 #[must_use = "this returns the result of the operation, \
1664 without modifying the original"]
1665 #[inline(always)]
1666 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1667 pub const unsafe fn unchecked_shr(self, rhs: u32) -> Self {
1668 assert_unsafe_precondition!(
1669 check_language_ub,
1670 concat!(stringify!($SelfT), "::unchecked_shr cannot overflow"),
1671 (
1672 rhs: u32 = rhs,
1673 ) => rhs < <$ActualT>::BITS,
1674 );
1675
1676 // SAFETY: this is guaranteed to be safe by the caller.
1677 unsafe {
1678 intrinsics::unchecked_shr(self, rhs)
1679 }
1680 }
1681
1682 /// Unbounded shift right. Computes `self >> rhs`, without bounding the value of `rhs`.
1683 ///
1684 /// If `rhs` is larger or equal to the number of bits in `self`,
1685 /// the entire value is shifted out, and `0` is returned.
1686 ///
1687 /// # Examples
1688 ///
1689 /// Basic usage:
1690 /// ```
1691 /// #![feature(unbounded_shifts)]
1692 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".unbounded_shr(4), 0x1);")]
1693 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".unbounded_shr(129), 0);")]
1694 /// ```
1695 #[unstable(feature = "unbounded_shifts", issue = "129375")]
1696 #[must_use = "this returns the result of the operation, \
1697 without modifying the original"]
1698 #[inline]
1699 pub const fn unbounded_shr(self, rhs: u32) -> $SelfT{
1700 if rhs < Self::BITS {
1701 // SAFETY:
1702 // rhs is just checked to be in-range above
1703 unsafe { self.unchecked_shr(rhs) }
1704 } else {
1705 0
1706 }
1707 }
1708
1709 /// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
1710 /// overflow occurred.
1711 ///
1712 /// # Examples
1713 ///
1714 /// Basic usage:
1715 ///
1716 /// ```
1717 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));")]
1718 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);")]
1719 /// ```
1720 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1721 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1722 #[must_use = "this returns the result of the operation, \
1723 without modifying the original"]
1724 #[inline]
1725 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
1726 if exp == 0 {
1727 return Some(1);
1728 }
1729 let mut base = self;
1730 let mut acc: Self = 1;
1731
1732 loop {
1733 if (exp & 1) == 1 {
1734 acc = try_opt!(acc.checked_mul(base));
1735 // since exp!=0, finally the exp must be 1.
1736 if exp == 1 {
1737 return Some(acc);
1738 }
1739 }
1740 exp /= 2;
1741 base = try_opt!(base.checked_mul(base));
1742 }
1743 }
1744
1745 /// Strict exponentiation. Computes `self.pow(exp)`, panicking if
1746 /// overflow occurred.
1747 ///
1748 /// # Panics
1749 ///
1750 /// ## Overflow behavior
1751 ///
1752 /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
1753 ///
1754 /// # Examples
1755 ///
1756 /// Basic usage:
1757 ///
1758 /// ```
1759 /// #![feature(strict_overflow_ops)]
1760 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".strict_pow(5), 32);")]
1761 /// ```
1762 ///
1763 /// The following panics because of overflow:
1764 ///
1765 /// ```should_panic
1766 /// #![feature(strict_overflow_ops)]
1767 #[doc = concat!("let _ = ", stringify!($SelfT), "::MAX.strict_pow(2);")]
1768 /// ```
1769 #[unstable(feature = "strict_overflow_ops", issue = "118260")]
1770 #[must_use = "this returns the result of the operation, \
1771 without modifying the original"]
1772 #[inline]
1773 #[track_caller]
1774 pub const fn strict_pow(self, mut exp: u32) -> Self {
1775 if exp == 0 {
1776 return 1;
1777 }
1778 let mut base = self;
1779 let mut acc: Self = 1;
1780
1781 loop {
1782 if (exp & 1) == 1 {
1783 acc = acc.strict_mul(base);
1784 // since exp!=0, finally the exp must be 1.
1785 if exp == 1 {
1786 return acc;
1787 }
1788 }
1789 exp /= 2;
1790 base = base.strict_mul(base);
1791 }
1792 }
1793
1794 /// Saturating integer addition. Computes `self + rhs`, saturating at
1795 /// the numeric bounds instead of overflowing.
1796 ///
1797 /// # Examples
1798 ///
1799 /// Basic usage:
1800 ///
1801 /// ```
1802 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);")]
1803 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(127), ", stringify!($SelfT), "::MAX);")]
1804 /// ```
1805 #[stable(feature = "rust1", since = "1.0.0")]
1806 #[must_use = "this returns the result of the operation, \
1807 without modifying the original"]
1808 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1809 #[inline(always)]
1810 pub const fn saturating_add(self, rhs: Self) -> Self {
1811 intrinsics::saturating_add(self, rhs)
1812 }
1813
1814 /// Saturating addition with a signed integer. Computes `self + rhs`,
1815 /// saturating at the numeric bounds instead of overflowing.
1816 ///
1817 /// # Examples
1818 ///
1819 /// Basic usage:
1820 ///
1821 /// ```
1822 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_signed(2), 3);")]
1823 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_signed(-2), 0);")]
1824 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).saturating_add_signed(4), ", stringify!($SelfT), "::MAX);")]
1825 /// ```
1826 #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
1827 #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
1828 #[must_use = "this returns the result of the operation, \
1829 without modifying the original"]
1830 #[inline]
1831 pub const fn saturating_add_signed(self, rhs: $SignedT) -> Self {
1832 let (res, overflow) = self.overflowing_add(rhs as Self);
1833 if overflow == (rhs < 0) {
1834 res
1835 } else if overflow {
1836 Self::MAX
1837 } else {
1838 0
1839 }
1840 }
1841
1842 /// Saturating integer subtraction. Computes `self - rhs`, saturating
1843 /// at the numeric bounds instead of overflowing.
1844 ///
1845 /// # Examples
1846 ///
1847 /// Basic usage:
1848 ///
1849 /// ```
1850 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);")]
1851 #[doc = concat!("assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);")]
1852 /// ```
1853 #[stable(feature = "rust1", since = "1.0.0")]
1854 #[must_use = "this returns the result of the operation, \
1855 without modifying the original"]
1856 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1857 #[inline(always)]
1858 pub const fn saturating_sub(self, rhs: Self) -> Self {
1859 intrinsics::saturating_sub(self, rhs)
1860 }
1861
1862 /// Saturating integer subtraction. Computes `self` - `rhs`, saturating at
1863 /// the numeric bounds instead of overflowing.
1864 ///
1865 /// # Examples
1866 ///
1867 /// Basic usage:
1868 ///
1869 /// ```
1870 /// #![feature(mixed_integer_ops_unsigned_sub)]
1871 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_sub_signed(2), 0);")]
1872 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_sub_signed(-2), 3);")]
1873 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).saturating_sub_signed(-4), ", stringify!($SelfT), "::MAX);")]
1874 /// ```
1875 #[unstable(feature = "mixed_integer_ops_unsigned_sub", issue = "126043")]
1876 #[must_use = "this returns the result of the operation, \
1877 without modifying the original"]
1878 #[inline]
1879 pub const fn saturating_sub_signed(self, rhs: $SignedT) -> Self {
1880 let (res, overflow) = self.overflowing_sub_signed(rhs);
1881
1882 if !overflow {
1883 res
1884 } else if rhs < 0 {
1885 Self::MAX
1886 } else {
1887 0
1888 }
1889 }
1890
1891 /// Saturating integer multiplication. Computes `self * rhs`,
1892 /// saturating at the numeric bounds instead of overflowing.
1893 ///
1894 /// # Examples
1895 ///
1896 /// Basic usage:
1897 ///
1898 /// ```
1899 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);")]
1900 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),"::MAX);")]
1901 /// ```
1902 #[stable(feature = "wrapping", since = "1.7.0")]
1903 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
1904 #[must_use = "this returns the result of the operation, \
1905 without modifying the original"]
1906 #[inline]
1907 pub const fn saturating_mul(self, rhs: Self) -> Self {
1908 match self.checked_mul(rhs) {
1909 Some(x) => x,
1910 None => Self::MAX,
1911 }
1912 }
1913
1914 /// Saturating integer division. Computes `self / rhs`, saturating at the
1915 /// numeric bounds instead of overflowing.
1916 ///
1917 /// # Panics
1918 ///
1919 /// This function will panic if `rhs` is zero.
1920 ///
1921 /// # Examples
1922 ///
1923 /// Basic usage:
1924 ///
1925 /// ```
1926 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".saturating_div(2), 2);")]
1927 ///
1928 /// ```
1929 #[stable(feature = "saturating_div", since = "1.58.0")]
1930 #[rustc_const_stable(feature = "saturating_div", since = "1.58.0")]
1931 #[must_use = "this returns the result of the operation, \
1932 without modifying the original"]
1933 #[inline]
1934 #[track_caller]
1935 pub const fn saturating_div(self, rhs: Self) -> Self {
1936 // on unsigned types, there is no overflow in integer division
1937 self.wrapping_div(rhs)
1938 }
1939
1940 /// Saturating integer exponentiation. Computes `self.pow(exp)`,
1941 /// saturating at the numeric bounds instead of overflowing.
1942 ///
1943 /// # Examples
1944 ///
1945 /// Basic usage:
1946 ///
1947 /// ```
1948 #[doc = concat!("assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);")]
1949 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);")]
1950 /// ```
1951 #[stable(feature = "no_panic_pow", since = "1.34.0")]
1952 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
1953 #[must_use = "this returns the result of the operation, \
1954 without modifying the original"]
1955 #[inline]
1956 pub const fn saturating_pow(self, exp: u32) -> Self {
1957 match self.checked_pow(exp) {
1958 Some(x) => x,
1959 None => Self::MAX,
1960 }
1961 }
1962
1963 /// Wrapping (modular) addition. Computes `self + rhs`,
1964 /// wrapping around at the boundary of the type.
1965 ///
1966 /// # Examples
1967 ///
1968 /// Basic usage:
1969 ///
1970 /// ```
1971 #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);")]
1972 #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);")]
1973 /// ```
1974 #[stable(feature = "rust1", since = "1.0.0")]
1975 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
1976 #[must_use = "this returns the result of the operation, \
1977 without modifying the original"]
1978 #[inline(always)]
1979 pub const fn wrapping_add(self, rhs: Self) -> Self {
1980 intrinsics::wrapping_add(self, rhs)
1981 }
1982
1983 /// Wrapping (modular) addition with a signed integer. Computes
1984 /// `self + rhs`, wrapping around at the boundary of the type.
1985 ///
1986 /// # Examples
1987 ///
1988 /// Basic usage:
1989 ///
1990 /// ```
1991 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_add_signed(2), 3);")]
1992 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_add_signed(-2), ", stringify!($SelfT), "::MAX);")]
1993 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).wrapping_add_signed(4), 1);")]
1994 /// ```
1995 #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
1996 #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
1997 #[must_use = "this returns the result of the operation, \
1998 without modifying the original"]
1999 #[inline]
2000 pub const fn wrapping_add_signed(self, rhs: $SignedT) -> Self {
2001 self.wrapping_add(rhs as Self)
2002 }
2003
2004 /// Wrapping (modular) subtraction. Computes `self - rhs`,
2005 /// wrapping around at the boundary of the type.
2006 ///
2007 /// # Examples
2008 ///
2009 /// Basic usage:
2010 ///
2011 /// ```
2012 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);")]
2013 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::MAX), 101);")]
2014 /// ```
2015 #[stable(feature = "rust1", since = "1.0.0")]
2016 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2017 #[must_use = "this returns the result of the operation, \
2018 without modifying the original"]
2019 #[inline(always)]
2020 pub const fn wrapping_sub(self, rhs: Self) -> Self {
2021 intrinsics::wrapping_sub(self, rhs)
2022 }
2023
2024 /// Wrapping (modular) subtraction with a signed integer. Computes
2025 /// `self - rhs`, wrapping around at the boundary of the type.
2026 ///
2027 /// # Examples
2028 ///
2029 /// Basic usage:
2030 ///
2031 /// ```
2032 /// #![feature(mixed_integer_ops_unsigned_sub)]
2033 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_sub_signed(2), ", stringify!($SelfT), "::MAX);")]
2034 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_sub_signed(-2), 3);")]
2035 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).wrapping_sub_signed(-4), 1);")]
2036 /// ```
2037 #[unstable(feature = "mixed_integer_ops_unsigned_sub", issue = "126043")]
2038 #[must_use = "this returns the result of the operation, \
2039 without modifying the original"]
2040 #[inline]
2041 pub const fn wrapping_sub_signed(self, rhs: $SignedT) -> Self {
2042 self.wrapping_sub(rhs as Self)
2043 }
2044
2045 /// Wrapping (modular) multiplication. Computes `self *
2046 /// rhs`, wrapping around at the boundary of the type.
2047 ///
2048 /// # Examples
2049 ///
2050 /// Basic usage:
2051 ///
2052 /// Please note that this example is shared between integer types.
2053 /// Which explains why `u8` is used here.
2054 ///
2055 /// ```
2056 /// assert_eq!(10u8.wrapping_mul(12), 120);
2057 /// assert_eq!(25u8.wrapping_mul(12), 44);
2058 /// ```
2059 #[stable(feature = "rust1", since = "1.0.0")]
2060 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2061 #[must_use = "this returns the result of the operation, \
2062 without modifying the original"]
2063 #[inline(always)]
2064 pub const fn wrapping_mul(self, rhs: Self) -> Self {
2065 intrinsics::wrapping_mul(self, rhs)
2066 }
2067
2068 /// Wrapping (modular) division. Computes `self / rhs`.
2069 ///
2070 /// Wrapped division on unsigned types is just normal division. There's
2071 /// no way wrapping could ever happen. This function exists so that all
2072 /// operations are accounted for in the wrapping operations.
2073 ///
2074 /// # Panics
2075 ///
2076 /// This function will panic if `rhs` is zero.
2077 ///
2078 /// # Examples
2079 ///
2080 /// Basic usage:
2081 ///
2082 /// ```
2083 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);")]
2084 /// ```
2085 #[stable(feature = "num_wrapping", since = "1.2.0")]
2086 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
2087 #[must_use = "this returns the result of the operation, \
2088 without modifying the original"]
2089 #[inline(always)]
2090 #[track_caller]
2091 pub const fn wrapping_div(self, rhs: Self) -> Self {
2092 self / rhs
2093 }
2094
2095 /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
2096 ///
2097 /// Wrapped division on unsigned types is just normal division. There's
2098 /// no way wrapping could ever happen. This function exists so that all
2099 /// operations are accounted for in the wrapping operations. Since, for
2100 /// the positive integers, all common definitions of division are equal,
2101 /// this is exactly equal to `self.wrapping_div(rhs)`.
2102 ///
2103 /// # Panics
2104 ///
2105 /// This function will panic if `rhs` is zero.
2106 ///
2107 /// # Examples
2108 ///
2109 /// Basic usage:
2110 ///
2111 /// ```
2112 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);")]
2113 /// ```
2114 #[stable(feature = "euclidean_division", since = "1.38.0")]
2115 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
2116 #[must_use = "this returns the result of the operation, \
2117 without modifying the original"]
2118 #[inline(always)]
2119 #[track_caller]
2120 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
2121 self / rhs
2122 }
2123
2124 /// Wrapping (modular) remainder. Computes `self % rhs`.
2125 ///
2126 /// Wrapped remainder calculation on unsigned types is just the regular
2127 /// remainder calculation. There's no way wrapping could ever happen.
2128 /// This function exists so that all operations are accounted for in the
2129 /// wrapping operations.
2130 ///
2131 /// # Panics
2132 ///
2133 /// This function will panic if `rhs` is zero.
2134 ///
2135 /// # Examples
2136 ///
2137 /// Basic usage:
2138 ///
2139 /// ```
2140 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);")]
2141 /// ```
2142 #[stable(feature = "num_wrapping", since = "1.2.0")]
2143 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
2144 #[must_use = "this returns the result of the operation, \
2145 without modifying the original"]
2146 #[inline(always)]
2147 #[track_caller]
2148 pub const fn wrapping_rem(self, rhs: Self) -> Self {
2149 self % rhs
2150 }
2151
2152 /// Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
2153 ///
2154 /// Wrapped modulo calculation on unsigned types is just the regular
2155 /// remainder calculation. There's no way wrapping could ever happen.
2156 /// This function exists so that all operations are accounted for in the
2157 /// wrapping operations. Since, for the positive integers, all common
2158 /// definitions of division are equal, this is exactly equal to
2159 /// `self.wrapping_rem(rhs)`.
2160 ///
2161 /// # Panics
2162 ///
2163 /// This function will panic if `rhs` is zero.
2164 ///
2165 /// # Examples
2166 ///
2167 /// Basic usage:
2168 ///
2169 /// ```
2170 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);")]
2171 /// ```
2172 #[stable(feature = "euclidean_division", since = "1.38.0")]
2173 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
2174 #[must_use = "this returns the result of the operation, \
2175 without modifying the original"]
2176 #[inline(always)]
2177 #[track_caller]
2178 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
2179 self % rhs
2180 }
2181
2182 /// Wrapping (modular) negation. Computes `-self`,
2183 /// wrapping around at the boundary of the type.
2184 ///
2185 /// Since unsigned types do not have negative equivalents
2186 /// all applications of this function will wrap (except for `-0`).
2187 /// For values smaller than the corresponding signed type's maximum
2188 /// the result is the same as casting the corresponding signed value.
2189 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
2190 /// `MAX` is the corresponding signed type's maximum.
2191 ///
2192 /// # Examples
2193 ///
2194 /// Basic usage:
2195 ///
2196 /// ```
2197 #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".wrapping_neg(), 0);")]
2198 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_neg(), 1);")]
2199 #[doc = concat!("assert_eq!(13_", stringify!($SelfT), ".wrapping_neg(), (!13) + 1);")]
2200 #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".wrapping_neg(), !(42 - 1));")]
2201 /// ```
2202 #[stable(feature = "num_wrapping", since = "1.2.0")]
2203 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2204 #[must_use = "this returns the result of the operation, \
2205 without modifying the original"]
2206 #[inline(always)]
2207 pub const fn wrapping_neg(self) -> Self {
2208 (0 as $SelfT).wrapping_sub(self)
2209 }
2210
2211 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
2212 /// where `mask` removes any high-order bits of `rhs` that
2213 /// would cause the shift to exceed the bitwidth of the type.
2214 ///
2215 /// Note that this is *not* the same as a rotate-left; the
2216 /// RHS of a wrapping shift-left is restricted to the range
2217 /// of the type, rather than the bits shifted out of the LHS
2218 /// being returned to the other end. The primitive integer
2219 /// types all implement a [`rotate_left`](Self::rotate_left) function,
2220 /// which may be what you want instead.
2221 ///
2222 /// # Examples
2223 ///
2224 /// Basic usage:
2225 ///
2226 /// ```
2227 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);")]
2228 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);")]
2229 /// ```
2230 #[stable(feature = "num_wrapping", since = "1.2.0")]
2231 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2232 #[must_use = "this returns the result of the operation, \
2233 without modifying the original"]
2234 #[inline(always)]
2235 pub const fn wrapping_shl(self, rhs: u32) -> Self {
2236 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
2237 // out of bounds
2238 unsafe {
2239 self.unchecked_shl(rhs & (Self::BITS - 1))
2240 }
2241 }
2242
2243 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
2244 /// where `mask` removes any high-order bits of `rhs` that
2245 /// would cause the shift to exceed the bitwidth of the type.
2246 ///
2247 /// Note that this is *not* the same as a rotate-right; the
2248 /// RHS of a wrapping shift-right is restricted to the range
2249 /// of the type, rather than the bits shifted out of the LHS
2250 /// being returned to the other end. The primitive integer
2251 /// types all implement a [`rotate_right`](Self::rotate_right) function,
2252 /// which may be what you want instead.
2253 ///
2254 /// # Examples
2255 ///
2256 /// Basic usage:
2257 ///
2258 /// ```
2259 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);")]
2260 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);")]
2261 /// ```
2262 #[stable(feature = "num_wrapping", since = "1.2.0")]
2263 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2264 #[must_use = "this returns the result of the operation, \
2265 without modifying the original"]
2266 #[inline(always)]
2267 pub const fn wrapping_shr(self, rhs: u32) -> Self {
2268 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
2269 // out of bounds
2270 unsafe {
2271 self.unchecked_shr(rhs & (Self::BITS - 1))
2272 }
2273 }
2274
2275 /// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
2276 /// wrapping around at the boundary of the type.
2277 ///
2278 /// # Examples
2279 ///
2280 /// Basic usage:
2281 ///
2282 /// ```
2283 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);")]
2284 /// assert_eq!(3u8.wrapping_pow(6), 217);
2285 /// ```
2286 #[stable(feature = "no_panic_pow", since = "1.34.0")]
2287 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2288 #[must_use = "this returns the result of the operation, \
2289 without modifying the original"]
2290 #[inline]
2291 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
2292 if exp == 0 {
2293 return 1;
2294 }
2295 let mut base = self;
2296 let mut acc: Self = 1;
2297
2298 if intrinsics::is_val_statically_known(exp) {
2299 while exp > 1 {
2300 if (exp & 1) == 1 {
2301 acc = acc.wrapping_mul(base);
2302 }
2303 exp /= 2;
2304 base = base.wrapping_mul(base);
2305 }
2306
2307 // since exp!=0, finally the exp must be 1.
2308 // Deal with the final bit of the exponent separately, since
2309 // squaring the base afterwards is not necessary.
2310 acc.wrapping_mul(base)
2311 } else {
2312 // This is faster than the above when the exponent is not known
2313 // at compile time. We can't use the same code for the constant
2314 // exponent case because LLVM is currently unable to unroll
2315 // this loop.
2316 loop {
2317 if (exp & 1) == 1 {
2318 acc = acc.wrapping_mul(base);
2319 // since exp!=0, finally the exp must be 1.
2320 if exp == 1 {
2321 return acc;
2322 }
2323 }
2324 exp /= 2;
2325 base = base.wrapping_mul(base);
2326 }
2327 }
2328 }
2329
2330 /// Calculates `self` + `rhs`.
2331 ///
2332 /// Returns a tuple of the addition along with a boolean indicating
2333 /// whether an arithmetic overflow would occur. If an overflow would
2334 /// have occurred then the wrapped value is returned.
2335 ///
2336 /// # Examples
2337 ///
2338 /// Basic usage:
2339 ///
2340 /// ```
2341 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));")]
2342 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));")]
2343 /// ```
2344 #[stable(feature = "wrapping", since = "1.7.0")]
2345 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2346 #[must_use = "this returns the result of the operation, \
2347 without modifying the original"]
2348 #[inline(always)]
2349 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
2350 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
2351 (a as Self, b)
2352 }
2353
2354 /// Calculates `self` + `rhs` + `carry` and returns a tuple containing
2355 /// the sum and the output carry.
2356 ///
2357 /// Performs "ternary addition" of two integer operands and a carry-in
2358 /// bit, and returns an output integer and a carry-out bit. This allows
2359 /// chaining together multiple additions to create a wider addition, and
2360 /// can be useful for bignum addition.
2361 ///
2362 #[doc = concat!("This can be thought of as a ", stringify!($BITS), "-bit \"full adder\", in the electronics sense.")]
2363 ///
2364 /// If the input carry is false, this method is equivalent to
2365 /// [`overflowing_add`](Self::overflowing_add), and the output carry is
2366 /// equal to the overflow flag. Note that although carry and overflow
2367 /// flags are similar for unsigned integers, they are different for
2368 /// signed integers.
2369 ///
2370 /// # Examples
2371 ///
2372 /// ```
2373 /// #![feature(bigint_helper_methods)]
2374 ///
2375 #[doc = concat!("// 3 MAX (a = 3 × 2^", stringify!($BITS), " + 2^", stringify!($BITS), " - 1)")]
2376 #[doc = concat!("// + 5 7 (b = 5 × 2^", stringify!($BITS), " + 7)")]
2377 /// // ---------
2378 #[doc = concat!("// 9 6 (sum = 9 × 2^", stringify!($BITS), " + 6)")]
2379 ///
2380 #[doc = concat!("let (a1, a0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (3, ", stringify!($SelfT), "::MAX);")]
2381 #[doc = concat!("let (b1, b0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (5, 7);")]
2382 /// let carry0 = false;
2383 ///
2384 /// let (sum0, carry1) = a0.carrying_add(b0, carry0);
2385 /// assert_eq!(carry1, true);
2386 /// let (sum1, carry2) = a1.carrying_add(b1, carry1);
2387 /// assert_eq!(carry2, false);
2388 ///
2389 /// assert_eq!((sum1, sum0), (9, 6));
2390 /// ```
2391 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
2392 #[rustc_const_unstable(feature = "bigint_helper_methods", issue = "85532")]
2393 #[must_use = "this returns the result of the operation, \
2394 without modifying the original"]
2395 #[inline]
2396 pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
2397 // note: longer-term this should be done via an intrinsic, but this has been shown
2398 // to generate optimal code for now, and LLVM doesn't have an equivalent intrinsic
2399 let (a, c1) = self.overflowing_add(rhs);
2400 let (b, c2) = a.overflowing_add(carry as $SelfT);
2401 // Ideally LLVM would know this is disjoint without us telling them,
2402 // but it doesn't <https://github.com/llvm/llvm-project/issues/118162>
2403 // SAFETY: Only one of `c1` and `c2` can be set.
2404 // For c1 to be set we need to have overflowed, but if we did then
2405 // `a` is at most `MAX-1`, which means that `c2` cannot possibly
2406 // overflow because it's adding at most `1` (since it came from `bool`)
2407 (b, unsafe { intrinsics::disjoint_bitor(c1, c2) })
2408 }
2409
2410 /// Calculates `self` + `rhs` with a signed `rhs`.
2411 ///
2412 /// Returns a tuple of the addition along with a boolean indicating
2413 /// whether an arithmetic overflow would occur. If an overflow would
2414 /// have occurred then the wrapped value is returned.
2415 ///
2416 /// # Examples
2417 ///
2418 /// Basic usage:
2419 ///
2420 /// ```
2421 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_signed(2), (3, false));")]
2422 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_signed(-2), (", stringify!($SelfT), "::MAX, true));")]
2423 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).overflowing_add_signed(4), (1, true));")]
2424 /// ```
2425 #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
2426 #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
2427 #[must_use = "this returns the result of the operation, \
2428 without modifying the original"]
2429 #[inline]
2430 pub const fn overflowing_add_signed(self, rhs: $SignedT) -> (Self, bool) {
2431 let (res, overflowed) = self.overflowing_add(rhs as Self);
2432 (res, overflowed ^ (rhs < 0))
2433 }
2434
2435 /// Calculates `self` - `rhs`.
2436 ///
2437 /// Returns a tuple of the subtraction along with a boolean indicating
2438 /// whether an arithmetic overflow would occur. If an overflow would
2439 /// have occurred then the wrapped value is returned.
2440 ///
2441 /// # Examples
2442 ///
2443 /// Basic usage:
2444 ///
2445 /// ```
2446 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));")]
2447 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")]
2448 /// ```
2449 #[stable(feature = "wrapping", since = "1.7.0")]
2450 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2451 #[must_use = "this returns the result of the operation, \
2452 without modifying the original"]
2453 #[inline(always)]
2454 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
2455 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
2456 (a as Self, b)
2457 }
2458
2459 /// Calculates `self` − `rhs` − `borrow` and returns a tuple
2460 /// containing the difference and the output borrow.
2461 ///
2462 /// Performs "ternary subtraction" by subtracting both an integer
2463 /// operand and a borrow-in bit from `self`, and returns an output
2464 /// integer and a borrow-out bit. This allows chaining together multiple
2465 /// subtractions to create a wider subtraction, and can be useful for
2466 /// bignum subtraction.
2467 ///
2468 /// # Examples
2469 ///
2470 /// ```
2471 /// #![feature(bigint_helper_methods)]
2472 ///
2473 #[doc = concat!("// 9 6 (a = 9 × 2^", stringify!($BITS), " + 6)")]
2474 #[doc = concat!("// - 5 7 (b = 5 × 2^", stringify!($BITS), " + 7)")]
2475 /// // ---------
2476 #[doc = concat!("// 3 MAX (diff = 3 × 2^", stringify!($BITS), " + 2^", stringify!($BITS), " - 1)")]
2477 ///
2478 #[doc = concat!("let (a1, a0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (9, 6);")]
2479 #[doc = concat!("let (b1, b0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (5, 7);")]
2480 /// let borrow0 = false;
2481 ///
2482 /// let (diff0, borrow1) = a0.borrowing_sub(b0, borrow0);
2483 /// assert_eq!(borrow1, true);
2484 /// let (diff1, borrow2) = a1.borrowing_sub(b1, borrow1);
2485 /// assert_eq!(borrow2, false);
2486 ///
2487 #[doc = concat!("assert_eq!((diff1, diff0), (3, ", stringify!($SelfT), "::MAX));")]
2488 /// ```
2489 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
2490 #[must_use = "this returns the result of the operation, \
2491 without modifying the original"]
2492 #[inline]
2493 pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
2494 // note: longer-term this should be done via an intrinsic, but this has been shown
2495 // to generate optimal code for now, and LLVM doesn't have an equivalent intrinsic
2496 let (a, b) = self.overflowing_sub(rhs);
2497 let (c, d) = a.overflowing_sub(borrow as $SelfT);
2498 (c, b | d)
2499 }
2500
2501 /// Calculates `self` - `rhs` with a signed `rhs`
2502 ///
2503 /// Returns a tuple of the subtraction along with a boolean indicating
2504 /// whether an arithmetic overflow would occur. If an overflow would
2505 /// have occurred then the wrapped value is returned.
2506 ///
2507 /// # Examples
2508 ///
2509 /// Basic usage:
2510 ///
2511 /// ```
2512 /// #![feature(mixed_integer_ops_unsigned_sub)]
2513 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_sub_signed(2), (", stringify!($SelfT), "::MAX, true));")]
2514 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_sub_signed(-2), (3, false));")]
2515 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).overflowing_sub_signed(-4), (1, true));")]
2516 /// ```
2517 #[unstable(feature = "mixed_integer_ops_unsigned_sub", issue = "126043")]
2518 #[must_use = "this returns the result of the operation, \
2519 without modifying the original"]
2520 #[inline]
2521 pub const fn overflowing_sub_signed(self, rhs: $SignedT) -> (Self, bool) {
2522 let (res, overflow) = self.overflowing_sub(rhs as Self);
2523
2524 (res, overflow ^ (rhs < 0))
2525 }
2526
2527 /// Computes the absolute difference between `self` and `other`.
2528 ///
2529 /// # Examples
2530 ///
2531 /// Basic usage:
2532 ///
2533 /// ```
2534 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(80), 20", stringify!($SelfT), ");")]
2535 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(110), 10", stringify!($SelfT), ");")]
2536 /// ```
2537 #[stable(feature = "int_abs_diff", since = "1.60.0")]
2538 #[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
2539 #[must_use = "this returns the result of the operation, \
2540 without modifying the original"]
2541 #[inline]
2542 pub const fn abs_diff(self, other: Self) -> Self {
2543 if mem::size_of::<Self>() == 1 {
2544 // Trick LLVM into generating the psadbw instruction when SSE2
2545 // is available and this function is autovectorized for u8's.
2546 (self as i32).wrapping_sub(other as i32).abs() as Self
2547 } else {
2548 if self < other {
2549 other - self
2550 } else {
2551 self - other
2552 }
2553 }
2554 }
2555
2556 /// Calculates the multiplication of `self` and `rhs`.
2557 ///
2558 /// Returns a tuple of the multiplication along with a boolean
2559 /// indicating whether an arithmetic overflow would occur. If an
2560 /// overflow would have occurred then the wrapped value is returned.
2561 ///
2562 /// # Examples
2563 ///
2564 /// Basic usage:
2565 ///
2566 /// Please note that this example is shared between integer types.
2567 /// Which explains why `u32` is used here.
2568 ///
2569 /// ```
2570 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
2571 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
2572 /// ```
2573 #[stable(feature = "wrapping", since = "1.7.0")]
2574 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2575 #[must_use = "this returns the result of the operation, \
2576 without modifying the original"]
2577 #[inline(always)]
2578 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
2579 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
2580 (a as Self, b)
2581 }
2582
2583 /// Calculates the complete product `self * rhs` without the possibility to overflow.
2584 ///
2585 /// This returns the low-order (wrapping) bits and the high-order (overflow) bits
2586 /// of the result as two separate values, in that order.
2587 ///
2588 /// If you also need to add a carry to the wide result, then you want
2589 /// [`Self::carrying_mul`] instead.
2590 ///
2591 /// # Examples
2592 ///
2593 /// Basic usage:
2594 ///
2595 /// Please note that this example is shared between integer types.
2596 /// Which explains why `u32` is used here.
2597 ///
2598 /// ```
2599 /// #![feature(bigint_helper_methods)]
2600 /// assert_eq!(5u32.widening_mul(2), (10, 0));
2601 /// assert_eq!(1_000_000_000u32.widening_mul(10), (1410065408, 2));
2602 /// ```
2603 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
2604 #[rustc_const_unstable(feature = "bigint_helper_methods", issue = "85532")]
2605 #[must_use = "this returns the result of the operation, \
2606 without modifying the original"]
2607 #[inline]
2608 pub const fn widening_mul(self, rhs: Self) -> (Self, Self) {
2609 Self::carrying_mul_add(self, rhs, 0, 0)
2610 }
2611
2612 /// Calculates the "full multiplication" `self * rhs + carry`
2613 /// without the possibility to overflow.
2614 ///
2615 /// This returns the low-order (wrapping) bits and the high-order (overflow) bits
2616 /// of the result as two separate values, in that order.
2617 ///
2618 /// Performs "long multiplication" which takes in an extra amount to add, and may return an
2619 /// additional amount of overflow. This allows for chaining together multiple
2620 /// multiplications to create "big integers" which represent larger values.
2621 ///
2622 /// If you don't need the `carry`, then you can use [`Self::widening_mul`] instead.
2623 ///
2624 /// # Examples
2625 ///
2626 /// Basic usage:
2627 ///
2628 /// Please note that this example is shared between integer types.
2629 /// Which explains why `u32` is used here.
2630 ///
2631 /// ```
2632 /// #![feature(bigint_helper_methods)]
2633 /// assert_eq!(5u32.carrying_mul(2, 0), (10, 0));
2634 /// assert_eq!(5u32.carrying_mul(2, 10), (20, 0));
2635 /// assert_eq!(1_000_000_000u32.carrying_mul(10, 0), (1410065408, 2));
2636 /// assert_eq!(1_000_000_000u32.carrying_mul(10, 10), (1410065418, 2));
2637 #[doc = concat!("assert_eq!(",
2638 stringify!($SelfT), "::MAX.carrying_mul(", stringify!($SelfT), "::MAX, ", stringify!($SelfT), "::MAX), ",
2639 "(0, ", stringify!($SelfT), "::MAX));"
2640 )]
2641 /// ```
2642 ///
2643 /// This is the core operation needed for scalar multiplication when
2644 /// implementing it for wider-than-native types.
2645 ///
2646 /// ```
2647 /// #![feature(bigint_helper_methods)]
2648 /// fn scalar_mul_eq(little_endian_digits: &mut Vec<u16>, multiplicand: u16) {
2649 /// let mut carry = 0;
2650 /// for d in little_endian_digits.iter_mut() {
2651 /// (*d, carry) = d.carrying_mul(multiplicand, carry);
2652 /// }
2653 /// if carry != 0 {
2654 /// little_endian_digits.push(carry);
2655 /// }
2656 /// }
2657 ///
2658 /// let mut v = vec![10, 20];
2659 /// scalar_mul_eq(&mut v, 3);
2660 /// assert_eq!(v, [30, 60]);
2661 ///
2662 /// assert_eq!(0x87654321_u64 * 0xFEED, 0x86D3D159E38D);
2663 /// let mut v = vec![0x4321, 0x8765];
2664 /// scalar_mul_eq(&mut v, 0xFEED);
2665 /// assert_eq!(v, [0xE38D, 0xD159, 0x86D3]);
2666 /// ```
2667 ///
2668 /// If `carry` is zero, this is similar to [`overflowing_mul`](Self::overflowing_mul),
2669 /// except that it gives the value of the overflow instead of just whether one happened:
2670 ///
2671 /// ```
2672 /// #![feature(bigint_helper_methods)]
2673 /// let r = u8::carrying_mul(7, 13, 0);
2674 /// assert_eq!((r.0, r.1 != 0), u8::overflowing_mul(7, 13));
2675 /// let r = u8::carrying_mul(13, 42, 0);
2676 /// assert_eq!((r.0, r.1 != 0), u8::overflowing_mul(13, 42));
2677 /// ```
2678 ///
2679 /// The value of the first field in the returned tuple matches what you'd get
2680 /// by combining the [`wrapping_mul`](Self::wrapping_mul) and
2681 /// [`wrapping_add`](Self::wrapping_add) methods:
2682 ///
2683 /// ```
2684 /// #![feature(bigint_helper_methods)]
2685 /// assert_eq!(
2686 /// 789_u16.carrying_mul(456, 123).0,
2687 /// 789_u16.wrapping_mul(456).wrapping_add(123),
2688 /// );
2689 /// ```
2690 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
2691 #[rustc_const_unstable(feature = "bigint_helper_methods", issue = "85532")]
2692 #[must_use = "this returns the result of the operation, \
2693 without modifying the original"]
2694 #[inline]
2695 pub const fn carrying_mul(self, rhs: Self, carry: Self) -> (Self, Self) {
2696 Self::carrying_mul_add(self, rhs, carry, 0)
2697 }
2698
2699 /// Calculates the "full multiplication" `self * rhs + carry1 + carry2`
2700 /// without the possibility to overflow.
2701 ///
2702 /// This returns the low-order (wrapping) bits and the high-order (overflow) bits
2703 /// of the result as two separate values, in that order.
2704 ///
2705 /// Performs "long multiplication" which takes in an extra amount to add, and may return an
2706 /// additional amount of overflow. This allows for chaining together multiple
2707 /// multiplications to create "big integers" which represent larger values.
2708 ///
2709 /// If you don't need either `carry`, then you can use [`Self::widening_mul`] instead,
2710 /// and if you only need one `carry`, then you can use [`Self::carrying_mul`] instead.
2711 ///
2712 /// # Examples
2713 ///
2714 /// Basic usage:
2715 ///
2716 /// Please note that this example is shared between integer types,
2717 /// which explains why `u32` is used here.
2718 ///
2719 /// ```
2720 /// #![feature(bigint_helper_methods)]
2721 /// assert_eq!(5u32.carrying_mul_add(2, 0, 0), (10, 0));
2722 /// assert_eq!(5u32.carrying_mul_add(2, 10, 10), (30, 0));
2723 /// assert_eq!(1_000_000_000u32.carrying_mul_add(10, 0, 0), (1410065408, 2));
2724 /// assert_eq!(1_000_000_000u32.carrying_mul_add(10, 10, 10), (1410065428, 2));
2725 #[doc = concat!("assert_eq!(",
2726 stringify!($SelfT), "::MAX.carrying_mul_add(", stringify!($SelfT), "::MAX, ", stringify!($SelfT), "::MAX, ", stringify!($SelfT), "::MAX), ",
2727 "(", stringify!($SelfT), "::MAX, ", stringify!($SelfT), "::MAX));"
2728 )]
2729 /// ```
2730 ///
2731 /// This is the core per-digit operation for "grade school" O(n²) multiplication.
2732 ///
2733 /// Please note that this example is shared between integer types,
2734 /// using `u8` for simplicity of the demonstration.
2735 ///
2736 /// ```
2737 /// #![feature(bigint_helper_methods)]
2738 ///
2739 /// fn quadratic_mul<const N: usize>(a: [u8; N], b: [u8; N]) -> [u8; N] {
2740 /// let mut out = [0; N];
2741 /// for j in 0..N {
2742 /// let mut carry = 0;
2743 /// for i in 0..(N - j) {
2744 /// (out[j + i], carry) = u8::carrying_mul_add(a[i], b[j], out[j + i], carry);
2745 /// }
2746 /// }
2747 /// out
2748 /// }
2749 ///
2750 /// // -1 * -1 == 1
2751 /// assert_eq!(quadratic_mul([0xFF; 3], [0xFF; 3]), [1, 0, 0]);
2752 ///
2753 /// assert_eq!(u32::wrapping_mul(0x9e3779b9, 0x7f4a7c15), 0xCFFC982D);
2754 /// assert_eq!(
2755 /// quadratic_mul(u32::to_le_bytes(0x9e3779b9), u32::to_le_bytes(0x7f4a7c15)),
2756 /// u32::to_le_bytes(0xCFFC982D)
2757 /// );
2758 /// ```
2759 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
2760 #[rustc_const_unstable(feature = "bigint_helper_methods", issue = "85532")]
2761 #[must_use = "this returns the result of the operation, \
2762 without modifying the original"]
2763 #[inline]
2764 pub const fn carrying_mul_add(self, rhs: Self, carry: Self, add: Self) -> (Self, Self) {
2765 intrinsics::carrying_mul_add(self, rhs, carry, add)
2766 }
2767
2768 /// Calculates the divisor when `self` is divided by `rhs`.
2769 ///
2770 /// Returns a tuple of the divisor along with a boolean indicating
2771 /// whether an arithmetic overflow would occur. Note that for unsigned
2772 /// integers overflow never occurs, so the second value is always
2773 /// `false`.
2774 ///
2775 /// # Panics
2776 ///
2777 /// This function will panic if `rhs` is zero.
2778 ///
2779 /// # Examples
2780 ///
2781 /// Basic usage:
2782 ///
2783 /// ```
2784 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));")]
2785 /// ```
2786 #[inline(always)]
2787 #[stable(feature = "wrapping", since = "1.7.0")]
2788 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
2789 #[must_use = "this returns the result of the operation, \
2790 without modifying the original"]
2791 #[track_caller]
2792 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
2793 (self / rhs, false)
2794 }
2795
2796 /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
2797 ///
2798 /// Returns a tuple of the divisor along with a boolean indicating
2799 /// whether an arithmetic overflow would occur. Note that for unsigned
2800 /// integers overflow never occurs, so the second value is always
2801 /// `false`.
2802 /// Since, for the positive integers, all common
2803 /// definitions of division are equal, this
2804 /// is exactly equal to `self.overflowing_div(rhs)`.
2805 ///
2806 /// # Panics
2807 ///
2808 /// This function will panic if `rhs` is zero.
2809 ///
2810 /// # Examples
2811 ///
2812 /// Basic usage:
2813 ///
2814 /// ```
2815 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));")]
2816 /// ```
2817 #[inline(always)]
2818 #[stable(feature = "euclidean_division", since = "1.38.0")]
2819 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
2820 #[must_use = "this returns the result of the operation, \
2821 without modifying the original"]
2822 #[track_caller]
2823 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
2824 (self / rhs, false)
2825 }
2826
2827 /// Calculates the remainder when `self` is divided by `rhs`.
2828 ///
2829 /// Returns a tuple of the remainder after dividing along with a boolean
2830 /// indicating whether an arithmetic overflow would occur. Note that for
2831 /// unsigned integers overflow never occurs, so the second value is
2832 /// always `false`.
2833 ///
2834 /// # Panics
2835 ///
2836 /// This function will panic if `rhs` is zero.
2837 ///
2838 /// # Examples
2839 ///
2840 /// Basic usage:
2841 ///
2842 /// ```
2843 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));")]
2844 /// ```
2845 #[inline(always)]
2846 #[stable(feature = "wrapping", since = "1.7.0")]
2847 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
2848 #[must_use = "this returns the result of the operation, \
2849 without modifying the original"]
2850 #[track_caller]
2851 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
2852 (self % rhs, false)
2853 }
2854
2855 /// Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
2856 ///
2857 /// Returns a tuple of the modulo after dividing along with a boolean
2858 /// indicating whether an arithmetic overflow would occur. Note that for
2859 /// unsigned integers overflow never occurs, so the second value is
2860 /// always `false`.
2861 /// Since, for the positive integers, all common
2862 /// definitions of division are equal, this operation
2863 /// is exactly equal to `self.overflowing_rem(rhs)`.
2864 ///
2865 /// # Panics
2866 ///
2867 /// This function will panic if `rhs` is zero.
2868 ///
2869 /// # Examples
2870 ///
2871 /// Basic usage:
2872 ///
2873 /// ```
2874 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));")]
2875 /// ```
2876 #[inline(always)]
2877 #[stable(feature = "euclidean_division", since = "1.38.0")]
2878 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
2879 #[must_use = "this returns the result of the operation, \
2880 without modifying the original"]
2881 #[track_caller]
2882 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
2883 (self % rhs, false)
2884 }
2885
2886 /// Negates self in an overflowing fashion.
2887 ///
2888 /// Returns `!self + 1` using wrapping operations to return the value
2889 /// that represents the negation of this unsigned value. Note that for
2890 /// positive unsigned values overflow always occurs, but negating 0 does
2891 /// not overflow.
2892 ///
2893 /// # Examples
2894 ///
2895 /// Basic usage:
2896 ///
2897 /// ```
2898 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));")]
2899 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT), ", true));")]
2900 /// ```
2901 #[inline(always)]
2902 #[stable(feature = "wrapping", since = "1.7.0")]
2903 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2904 #[must_use = "this returns the result of the operation, \
2905 without modifying the original"]
2906 pub const fn overflowing_neg(self) -> (Self, bool) {
2907 ((!self).wrapping_add(1), self != 0)
2908 }
2909
2910 /// Shifts self left by `rhs` bits.
2911 ///
2912 /// Returns a tuple of the shifted version of self along with a boolean
2913 /// indicating whether the shift value was larger than or equal to the
2914 /// number of bits. If the shift value is too large, then value is
2915 /// masked (N-1) where N is the number of bits, and this value is then
2916 /// used to perform the shift.
2917 ///
2918 /// # Examples
2919 ///
2920 /// Basic usage:
2921 ///
2922 /// ```
2923 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));")]
2924 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));")]
2925 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shl(", stringify!($BITS_MINUS_ONE), "), (0, false));")]
2926 /// ```
2927 #[stable(feature = "wrapping", since = "1.7.0")]
2928 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2929 #[must_use = "this returns the result of the operation, \
2930 without modifying the original"]
2931 #[inline(always)]
2932 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
2933 (self.wrapping_shl(rhs), rhs >= Self::BITS)
2934 }
2935
2936 /// Shifts self right by `rhs` bits.
2937 ///
2938 /// Returns a tuple of the shifted version of self along with a boolean
2939 /// indicating whether the shift value was larger than or equal to the
2940 /// number of bits. If the shift value is too large, then value is
2941 /// masked (N-1) where N is the number of bits, and this value is then
2942 /// used to perform the shift.
2943 ///
2944 /// # Examples
2945 ///
2946 /// Basic usage:
2947 ///
2948 /// ```
2949 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));")]
2950 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));")]
2951 /// ```
2952 #[stable(feature = "wrapping", since = "1.7.0")]
2953 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2954 #[must_use = "this returns the result of the operation, \
2955 without modifying the original"]
2956 #[inline(always)]
2957 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
2958 (self.wrapping_shr(rhs), rhs >= Self::BITS)
2959 }
2960
2961 /// Raises self to the power of `exp`, using exponentiation by squaring.
2962 ///
2963 /// Returns a tuple of the exponentiation along with a bool indicating
2964 /// whether an overflow happened.
2965 ///
2966 /// # Examples
2967 ///
2968 /// Basic usage:
2969 ///
2970 /// ```
2971 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));")]
2972 /// assert_eq!(3u8.overflowing_pow(6), (217, true));
2973 /// ```
2974 #[stable(feature = "no_panic_pow", since = "1.34.0")]
2975 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2976 #[must_use = "this returns the result of the operation, \
2977 without modifying the original"]
2978 #[inline]
2979 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
2980 if exp == 0{
2981 return (1,false);
2982 }
2983 let mut base = self;
2984 let mut acc: Self = 1;
2985 let mut overflown = false;
2986 // Scratch space for storing results of overflowing_mul.
2987 let mut r;
2988
2989 loop {
2990 if (exp & 1) == 1 {
2991 r = acc.overflowing_mul(base);
2992 // since exp!=0, finally the exp must be 1.
2993 if exp == 1 {
2994 r.1 |= overflown;
2995 return r;
2996 }
2997 acc = r.0;
2998 overflown |= r.1;
2999 }
3000 exp /= 2;
3001 r = base.overflowing_mul(base);
3002 base = r.0;
3003 overflown |= r.1;
3004 }
3005 }
3006
3007 /// Raises self to the power of `exp`, using exponentiation by squaring.
3008 ///
3009 /// # Examples
3010 ///
3011 /// Basic usage:
3012 ///
3013 /// ```
3014 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".pow(5), 32);")]
3015 /// ```
3016 #[stable(feature = "rust1", since = "1.0.0")]
3017 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
3018 #[must_use = "this returns the result of the operation, \
3019 without modifying the original"]
3020 #[inline]
3021 #[rustc_inherit_overflow_checks]
3022 pub const fn pow(self, mut exp: u32) -> Self {
3023 if exp == 0 {
3024 return 1;
3025 }
3026 let mut base = self;
3027 let mut acc = 1;
3028
3029 if intrinsics::is_val_statically_known(exp) {
3030 while exp > 1 {
3031 if (exp & 1) == 1 {
3032 acc = acc * base;
3033 }
3034 exp /= 2;
3035 base = base * base;
3036 }
3037
3038 // since exp!=0, finally the exp must be 1.
3039 // Deal with the final bit of the exponent separately, since
3040 // squaring the base afterwards is not necessary and may cause a
3041 // needless overflow.
3042 acc * base
3043 } else {
3044 // This is faster than the above when the exponent is not known
3045 // at compile time. We can't use the same code for the constant
3046 // exponent case because LLVM is currently unable to unroll
3047 // this loop.
3048 loop {
3049 if (exp & 1) == 1 {
3050 acc = acc * base;
3051 // since exp!=0, finally the exp must be 1.
3052 if exp == 1 {
3053 return acc;
3054 }
3055 }
3056 exp /= 2;
3057 base = base * base;
3058 }
3059 }
3060 }
3061
3062 /// Returns the square root of the number, rounded down.
3063 ///
3064 /// # Examples
3065 ///
3066 /// Basic usage:
3067 /// ```
3068 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".isqrt(), 3);")]
3069 /// ```
3070 #[stable(feature = "isqrt", since = "1.84.0")]
3071 #[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
3072 #[must_use = "this returns the result of the operation, \
3073 without modifying the original"]
3074 #[inline]
3075 pub const fn isqrt(self) -> Self {
3076 let result = crate::num::int_sqrt::$ActualT(self as $ActualT) as $SelfT;
3077
3078 // Inform the optimizer what the range of outputs is. If testing
3079 // `core` crashes with no panic message and a `num::int_sqrt::u*`
3080 // test failed, it's because your edits caused these assertions or
3081 // the assertions in `fn isqrt` of `nonzero.rs` to become false.
3082 //
3083 // SAFETY: Integer square root is a monotonically nondecreasing
3084 // function, which means that increasing the input will never
3085 // cause the output to decrease. Thus, since the input for unsigned
3086 // integers is bounded by `[0, <$ActualT>::MAX]`, sqrt(n) will be
3087 // bounded by `[sqrt(0), sqrt(<$ActualT>::MAX)]`.
3088 unsafe {
3089 const MAX_RESULT: $SelfT = crate::num::int_sqrt::$ActualT(<$ActualT>::MAX) as $SelfT;
3090 crate::hint::assert_unchecked(result <= MAX_RESULT);
3091 }
3092
3093 result
3094 }
3095
3096 /// Performs Euclidean division.
3097 ///
3098 /// Since, for the positive integers, all common
3099 /// definitions of division are equal, this
3100 /// is exactly equal to `self / rhs`.
3101 ///
3102 /// # Panics
3103 ///
3104 /// This function will panic if `rhs` is zero.
3105 ///
3106 /// # Examples
3107 ///
3108 /// Basic usage:
3109 ///
3110 /// ```
3111 #[doc = concat!("assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type")]
3112 /// ```
3113 #[stable(feature = "euclidean_division", since = "1.38.0")]
3114 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
3115 #[must_use = "this returns the result of the operation, \
3116 without modifying the original"]
3117 #[inline(always)]
3118 #[track_caller]
3119 pub const fn div_euclid(self, rhs: Self) -> Self {
3120 self / rhs
3121 }
3122
3123
3124 /// Calculates the least remainder of `self (mod rhs)`.
3125 ///
3126 /// Since, for the positive integers, all common
3127 /// definitions of division are equal, this
3128 /// is exactly equal to `self % rhs`.
3129 ///
3130 /// # Panics
3131 ///
3132 /// This function will panic if `rhs` is zero.
3133 ///
3134 /// # Examples
3135 ///
3136 /// Basic usage:
3137 ///
3138 /// ```
3139 #[doc = concat!("assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type")]
3140 /// ```
3141 #[doc(alias = "modulo", alias = "mod")]
3142 #[stable(feature = "euclidean_division", since = "1.38.0")]
3143 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
3144 #[must_use = "this returns the result of the operation, \
3145 without modifying the original"]
3146 #[inline(always)]
3147 #[track_caller]
3148 pub const fn rem_euclid(self, rhs: Self) -> Self {
3149 self % rhs
3150 }
3151
3152 /// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
3153 ///
3154 /// This is the same as performing `self / rhs` for all unsigned integers.
3155 ///
3156 /// # Panics
3157 ///
3158 /// This function will panic if `rhs` is zero.
3159 ///
3160 /// # Examples
3161 ///
3162 /// Basic usage:
3163 ///
3164 /// ```
3165 /// #![feature(int_roundings)]
3166 #[doc = concat!("assert_eq!(7_", stringify!($SelfT), ".div_floor(4), 1);")]
3167 /// ```
3168 #[unstable(feature = "int_roundings", issue = "88581")]
3169 #[must_use = "this returns the result of the operation, \
3170 without modifying the original"]
3171 #[inline(always)]
3172 #[track_caller]
3173 pub const fn div_floor(self, rhs: Self) -> Self {
3174 self / rhs
3175 }
3176
3177 /// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
3178 ///
3179 /// # Panics
3180 ///
3181 /// This function will panic if `rhs` is zero.
3182 ///
3183 /// # Examples
3184 ///
3185 /// Basic usage:
3186 ///
3187 /// ```
3188 #[doc = concat!("assert_eq!(7_", stringify!($SelfT), ".div_ceil(4), 2);")]
3189 /// ```
3190 #[stable(feature = "int_roundings1", since = "1.73.0")]
3191 #[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
3192 #[must_use = "this returns the result of the operation, \
3193 without modifying the original"]
3194 #[inline]
3195 #[track_caller]
3196 pub const fn div_ceil(self, rhs: Self) -> Self {
3197 let d = self / rhs;
3198 let r = self % rhs;
3199 if r > 0 {
3200 d + 1
3201 } else {
3202 d
3203 }
3204 }
3205
3206 /// Calculates the smallest value greater than or equal to `self` that
3207 /// is a multiple of `rhs`.
3208 ///
3209 /// # Panics
3210 ///
3211 /// This function will panic if `rhs` is zero.
3212 ///
3213 /// ## Overflow behavior
3214 ///
3215 /// On overflow, this function will panic if overflow checks are enabled (default in debug
3216 /// mode) and wrap if overflow checks are disabled (default in release mode).
3217 ///
3218 /// # Examples
3219 ///
3220 /// Basic usage:
3221 ///
3222 /// ```
3223 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".next_multiple_of(8), 16);")]
3224 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".next_multiple_of(8), 24);")]
3225 /// ```
3226 #[stable(feature = "int_roundings1", since = "1.73.0")]
3227 #[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
3228 #[must_use = "this returns the result of the operation, \
3229 without modifying the original"]
3230 #[inline]
3231 #[rustc_inherit_overflow_checks]
3232 pub const fn next_multiple_of(self, rhs: Self) -> Self {
3233 match self % rhs {
3234 0 => self,
3235 r => self + (rhs - r)
3236 }
3237 }
3238
3239 /// Calculates the smallest value greater than or equal to `self` that
3240 /// is a multiple of `rhs`. Returns `None` if `rhs` is zero or the
3241 /// operation would result in overflow.
3242 ///
3243 /// # Examples
3244 ///
3245 /// Basic usage:
3246 ///
3247 /// ```
3248 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(16));")]
3249 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(24));")]
3250 #[doc = concat!("assert_eq!(1_", stringify!($SelfT), ".checked_next_multiple_of(0), None);")]
3251 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_multiple_of(2), None);")]
3252 /// ```
3253 #[stable(feature = "int_roundings1", since = "1.73.0")]
3254 #[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
3255 #[must_use = "this returns the result of the operation, \
3256 without modifying the original"]
3257 #[inline]
3258 pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
3259 match try_opt!(self.checked_rem(rhs)) {
3260 0 => Some(self),
3261 // rhs - r cannot overflow because r is smaller than rhs
3262 r => self.checked_add(rhs - r)
3263 }
3264 }
3265
3266 /// Returns `true` if `self` is an integer multiple of `rhs`, and false otherwise.
3267 ///
3268 /// This function is equivalent to `self % rhs == 0`, except that it will not panic
3269 /// for `rhs == 0`. Instead, `0.is_multiple_of(0) == true`, and for any non-zero `n`,
3270 /// `n.is_multiple_of(0) == false`.
3271 ///
3272 /// # Examples
3273 ///
3274 /// Basic usage:
3275 ///
3276 /// ```
3277 /// #![feature(unsigned_is_multiple_of)]
3278 #[doc = concat!("assert!(6_", stringify!($SelfT), ".is_multiple_of(2));")]
3279 #[doc = concat!("assert!(!5_", stringify!($SelfT), ".is_multiple_of(2));")]
3280 ///
3281 #[doc = concat!("assert!(0_", stringify!($SelfT), ".is_multiple_of(0));")]
3282 #[doc = concat!("assert!(!6_", stringify!($SelfT), ".is_multiple_of(0));")]
3283 /// ```
3284 #[unstable(feature = "unsigned_is_multiple_of", issue = "128101")]
3285 #[must_use]
3286 #[inline]
3287 #[rustc_inherit_overflow_checks]
3288 pub const fn is_multiple_of(self, rhs: Self) -> bool {
3289 match rhs {
3290 0 => self == 0,
3291 _ => self % rhs == 0,
3292 }
3293 }
3294
3295 /// Returns `true` if and only if `self == 2^k` for some `k`.
3296 ///
3297 /// # Examples
3298 ///
3299 /// Basic usage:
3300 ///
3301 /// ```
3302 #[doc = concat!("assert!(16", stringify!($SelfT), ".is_power_of_two());")]
3303 #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_power_of_two());")]
3304 /// ```
3305 #[must_use]
3306 #[stable(feature = "rust1", since = "1.0.0")]
3307 #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
3308 #[inline(always)]
3309 pub const fn is_power_of_two(self) -> bool {
3310 self.count_ones() == 1
3311 }
3312
3313 // Returns one less than next power of two.
3314 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
3315 //
3316 // 8u8.one_less_than_next_power_of_two() == 7
3317 // 6u8.one_less_than_next_power_of_two() == 7
3318 //
3319 // This method cannot overflow, as in the `next_power_of_two`
3320 // overflow cases it instead ends up returning the maximum value
3321 // of the type, and can return 0 for 0.
3322 #[inline]
3323 const fn one_less_than_next_power_of_two(self) -> Self {
3324 if self <= 1 { return 0; }
3325
3326 let p = self - 1;
3327 // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros.
3328 // That means the shift is always in-bounds, and some processors
3329 // (such as intel pre-haswell) have more efficient ctlz
3330 // intrinsics when the argument is non-zero.
3331 let z = unsafe { intrinsics::ctlz_nonzero(p) };
3332 <$SelfT>::MAX >> z
3333 }
3334
3335 /// Returns the smallest power of two greater than or equal to `self`.
3336 ///
3337 /// When return value overflows (i.e., `self > (1 << (N-1))` for type
3338 /// `uN`), it panics in debug mode and the return value is wrapped to 0 in
3339 /// release mode (the only situation in which this method can return 0).
3340 ///
3341 /// # Examples
3342 ///
3343 /// Basic usage:
3344 ///
3345 /// ```
3346 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);")]
3347 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);")]
3348 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".next_power_of_two(), 1);")]
3349 /// ```
3350 #[stable(feature = "rust1", since = "1.0.0")]
3351 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
3352 #[must_use = "this returns the result of the operation, \
3353 without modifying the original"]
3354 #[inline]
3355 #[rustc_inherit_overflow_checks]
3356 pub const fn next_power_of_two(self) -> Self {
3357 self.one_less_than_next_power_of_two() + 1
3358 }
3359
3360 /// Returns the smallest power of two greater than or equal to `self`. If
3361 /// the next power of two is greater than the type's maximum value,
3362 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
3363 ///
3364 /// # Examples
3365 ///
3366 /// Basic usage:
3367 ///
3368 /// ```
3369 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_next_power_of_two(), Some(2));")]
3370 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));")]
3371 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_power_of_two(), None);")]
3372 /// ```
3373 #[inline]
3374 #[stable(feature = "rust1", since = "1.0.0")]
3375 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
3376 #[must_use = "this returns the result of the operation, \
3377 without modifying the original"]
3378 pub const fn checked_next_power_of_two(self) -> Option<Self> {
3379 self.one_less_than_next_power_of_two().checked_add(1)
3380 }
3381
3382 /// Returns the smallest power of two greater than or equal to `n`. If
3383 /// the next power of two is greater than the type's maximum value,
3384 /// the return value is wrapped to `0`.
3385 ///
3386 /// # Examples
3387 ///
3388 /// Basic usage:
3389 ///
3390 /// ```
3391 /// #![feature(wrapping_next_power_of_two)]
3392 ///
3393 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);")]
3394 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);")]
3395 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_next_power_of_two(), 0);")]
3396 /// ```
3397 #[inline]
3398 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
3399 reason = "needs decision on wrapping behavior")]
3400 #[must_use = "this returns the result of the operation, \
3401 without modifying the original"]
3402 pub const fn wrapping_next_power_of_two(self) -> Self {
3403 self.one_less_than_next_power_of_two().wrapping_add(1)
3404 }
3405
3406 /// Returns the memory representation of this integer as a byte array in
3407 /// big-endian (network) byte order.
3408 ///
3409 #[doc = $to_xe_bytes_doc]
3410 ///
3411 /// # Examples
3412 ///
3413 /// ```
3414 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();")]
3415 #[doc = concat!("assert_eq!(bytes, ", $be_bytes, ");")]
3416 /// ```
3417 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3418 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3419 #[must_use = "this returns the result of the operation, \
3420 without modifying the original"]
3421 #[inline]
3422 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
3423 self.to_be().to_ne_bytes()
3424 }
3425
3426 /// Returns the memory representation of this integer as a byte array in
3427 /// little-endian byte order.
3428 ///
3429 #[doc = $to_xe_bytes_doc]
3430 ///
3431 /// # Examples
3432 ///
3433 /// ```
3434 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();")]
3435 #[doc = concat!("assert_eq!(bytes, ", $le_bytes, ");")]
3436 /// ```
3437 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3438 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3439 #[must_use = "this returns the result of the operation, \
3440 without modifying the original"]
3441 #[inline]
3442 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
3443 self.to_le().to_ne_bytes()
3444 }
3445
3446 /// Returns the memory representation of this integer as a byte array in
3447 /// native byte order.
3448 ///
3449 /// As the target platform's native endianness is used, portable code
3450 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
3451 /// instead.
3452 ///
3453 #[doc = $to_xe_bytes_doc]
3454 ///
3455 /// [`to_be_bytes`]: Self::to_be_bytes
3456 /// [`to_le_bytes`]: Self::to_le_bytes
3457 ///
3458 /// # Examples
3459 ///
3460 /// ```
3461 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();")]
3462 /// assert_eq!(
3463 /// bytes,
3464 /// if cfg!(target_endian = "big") {
3465 #[doc = concat!(" ", $be_bytes)]
3466 /// } else {
3467 #[doc = concat!(" ", $le_bytes)]
3468 /// }
3469 /// );
3470 /// ```
3471 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3472 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3473 #[must_use = "this returns the result of the operation, \
3474 without modifying the original"]
3475 // SAFETY: const sound because integers are plain old datatypes so we can always
3476 // transmute them to arrays of bytes
3477 #[inline]
3478 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
3479 // SAFETY: integers are plain old datatypes so we can always transmute them to
3480 // arrays of bytes
3481 unsafe { mem::transmute(self) }
3482 }
3483
3484 /// Creates a native endian integer value from its representation
3485 /// as a byte array in big endian.
3486 ///
3487 #[doc = $from_xe_bytes_doc]
3488 ///
3489 /// # Examples
3490 ///
3491 /// ```
3492 #[doc = concat!("let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");")]
3493 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
3494 /// ```
3495 ///
3496 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
3497 ///
3498 /// ```
3499 #[doc = concat!("fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
3500 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
3501 /// *input = rest;
3502 #[doc = concat!(" ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())")]
3503 /// }
3504 /// ```
3505 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3506 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3507 #[must_use]
3508 #[inline]
3509 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3510 Self::from_be(Self::from_ne_bytes(bytes))
3511 }
3512
3513 /// Creates a native endian integer value from its representation
3514 /// as a byte array in little endian.
3515 ///
3516 #[doc = $from_xe_bytes_doc]
3517 ///
3518 /// # Examples
3519 ///
3520 /// ```
3521 #[doc = concat!("let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");")]
3522 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
3523 /// ```
3524 ///
3525 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
3526 ///
3527 /// ```
3528 #[doc = concat!("fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
3529 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
3530 /// *input = rest;
3531 #[doc = concat!(" ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())")]
3532 /// }
3533 /// ```
3534 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3535 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3536 #[must_use]
3537 #[inline]
3538 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3539 Self::from_le(Self::from_ne_bytes(bytes))
3540 }
3541
3542 /// Creates a native endian integer value from its memory representation
3543 /// as a byte array in native endianness.
3544 ///
3545 /// As the target platform's native endianness is used, portable code
3546 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
3547 /// appropriate instead.
3548 ///
3549 /// [`from_be_bytes`]: Self::from_be_bytes
3550 /// [`from_le_bytes`]: Self::from_le_bytes
3551 ///
3552 #[doc = $from_xe_bytes_doc]
3553 ///
3554 /// # Examples
3555 ///
3556 /// ```
3557 #[doc = concat!("let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {")]
3558 #[doc = concat!(" ", $be_bytes, "")]
3559 /// } else {
3560 #[doc = concat!(" ", $le_bytes, "")]
3561 /// });
3562 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
3563 /// ```
3564 ///
3565 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
3566 ///
3567 /// ```
3568 #[doc = concat!("fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
3569 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")]
3570 /// *input = rest;
3571 #[doc = concat!(" ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())")]
3572 /// }
3573 /// ```
3574 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3575 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3576 #[must_use]
3577 // SAFETY: const sound because integers are plain old datatypes so we can always
3578 // transmute to them
3579 #[inline]
3580 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3581 // SAFETY: integers are plain old datatypes so we can always transmute to them
3582 unsafe { mem::transmute(bytes) }
3583 }
3584
3585 /// New code should prefer to use
3586 #[doc = concat!("[`", stringify!($SelfT), "::MIN", "`] instead.")]
3587 ///
3588 /// Returns the smallest value that can be represented by this integer type.
3589 #[stable(feature = "rust1", since = "1.0.0")]
3590 #[rustc_promotable]
3591 #[inline(always)]
3592 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
3593 #[deprecated(since = "TBD", note = "replaced by the `MIN` associated constant on this type")]
3594 #[rustc_diagnostic_item = concat!(stringify!($SelfT), "_legacy_fn_min_value")]
3595 pub const fn min_value() -> Self { Self::MIN }
3596
3597 /// New code should prefer to use
3598 #[doc = concat!("[`", stringify!($SelfT), "::MAX", "`] instead.")]
3599 ///
3600 /// Returns the largest value that can be represented by this integer type.
3601 #[stable(feature = "rust1", since = "1.0.0")]
3602 #[rustc_promotable]
3603 #[inline(always)]
3604 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
3605 #[deprecated(since = "TBD", note = "replaced by the `MAX` associated constant on this type")]
3606 #[rustc_diagnostic_item = concat!(stringify!($SelfT), "_legacy_fn_max_value")]
3607 pub const fn max_value() -> Self { Self::MAX }
3608 }
3609}