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