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