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