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