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