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