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