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