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