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