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