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