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