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