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