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