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