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