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