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