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