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