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