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