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