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