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